如何在用户脚本中处理多个 AJAX 结果?

2023-05-15前端开发问题
6

本文介绍了如何在用户脚本中处理多个 AJAX 结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我目前正在开发一个 Greasemonkey 脚本来翻译 Intranet 应用程序中的 <textarea> 字段,使用 Google Translation API.

I'm currently developing a Greasemonkey script to translate <textarea> fields in an Intranet app, using Google Translation API.

但有些文本太大而无法仅通过一个请求进行翻译.尝试时出现此错误:

But some texts are way too large to be translated with only one request. I get this error when trying :

请求实体太大

无论如何,我找到了一种将文本分割成片段的方法,并在单独的请求中发送它们.棘手的地方是,我应该如何替换原始文本区域中的这些片段,尤其是在正确的位置.

Anyway, I found a way to cut the texts in fragments, and send them in separate requests. Where it gets tricky, is how I should replace those fragments in their original textareas, and especially at the right place.

在尝试了几种方法都没有成功后,我在文本区域中插入了占位符,对应于需要翻译的文本片段:

After trying several methods without any success, I inserted placeholders in the textarea, corresponding to the fragments of text that have to be translated :

{1}
{2}
...

但是现在在我的 XHR 的成功回调中,我必须用翻译后的文本替换占位符.问题是,我的 XHR 在 for 循环中,遍历包含原始文本片段的表,当请求完成时,循环很长,我不知道如何获取把翻译放在哪里.

But now in the success callback of my XHR, I have to replace the placeholder with the translated text. The thing is, my XHR is inside a for loop, iterating over my table containing the fragments of original text, and when the requests finish, the loop is long finished and I don't know how to get where to put the translation.

代码如下:

//Array text[] contains the fragments of original text
var translated_text = [];
var l = text.length;
for(var i = 0; i < l; i++)
{
var fullurl = apiurl+encodeURIComponent(text[i]);
GM_xmlhttpRequest({
    method: 'GET',
    url: fullurl,
    headers:
    {
        'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey',
        'Accept': 'application/atom+xml,application/xml,text/xml',
    },
    onload: function(responseDetails)
    {
        var destination = "{"+i+"}";
        if(responseDetails.status == 200)
        {
            var data = $.parseJSON(responseDetails.responseText);
            translated_text[i] = data.responseData.translatedText.replace(/&quot;/g,""").replace(/&#39;/g,""").replace(/&gt;/g,">");
            textarea.text(textarea.text().replace("{"+i+"}",translated_text[i]));
        }
        else
        {
            alert('Request Failed : '+responseDetails.status+"
Error : "+responseDetails.statusText);
        }
    }
});
}

PS : 我不能使用 jQuery 的 AJAX 方法,因为这是一个跨域请求,所以这里不能使用新的 $.when 功能(遗憾)

PS : I cannot use jQuery's AJAX methods, because this is a Cross Domain request, so the new $.when functionality cannot be used here (sadly)

推荐答案

更新:使用较新版本的 Greasemonkey 和 Tampermonkey,您现在可以通过 a contextDoc:

Update: With newer versions of Greasemonkey and Tampermonkey, you can now pass a contextDoc:

GM_xmlhttpRequest ( {
   method:   'GET',
   url:      fullurl,
   context:  i,
   headers:  {
               'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey',
               'Accept': 'application/atom+xml,application/xml,text/xml',
             },
   onload:   function (responseDetails) {
                var destination = "{" + responseDetails.context + "}";  // context is `i`
                if (responseDetails.status == 200) {
                   var data           = $.parseJSON (responseDetails.responseText);
                   translated_text[i] = data.responseData.translatedText.replace (/&quot;/g,""")
                                      .replace (/&#39;/g,""").replace (/&gt;/g,">")
                                      ;
                   textarea.text (textarea.text ().replace ("{"+i+"}",translated_text[i]) );
                }
                else {
                   alert (
                      'Request Failed : '+responseDetails.status+"
Error : "
                      + responseDetails.statusText
                   );
                }
             }
} );

<小时>

对于其他/较旧的平台,要使用 i 的值,您需要 将其包装在 JavaScript 闭包. 一种方法是:


For other/older platforms, to use the value of i, you need to wrap it in a JavaScript closure. One way to do do that is:

( function (i)  {
   GM_xmlhttpRequest ( {
      method:   'GET',
      url:      fullurl,
      headers:  {
                  'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey',
                  'Accept': 'application/atom+xml,application/xml,text/xml',
                },
      onload:   function (responseDetails) {
                   var destination = "{"+i+"}";
                   if (responseDetails.status == 200) {
                      var data           = $.parseJSON (responseDetails.responseText);
                      translated_text[i] = data.responseData.translatedText.replace (/&quot;/g,""")
                                         .replace (/&#39;/g,""").replace (/&gt;/g,">")
                                         ;
                      textarea.text (textarea.text ().replace ("{"+i+"}",translated_text[i]) );
                   }
                   else {
                      alert (
                         'Request Failed : '+responseDetails.status+"
Error : "
                         + responseDetails.statusText
                      );
                   }
                }
   } );
} ) (i);

这篇关于如何在用户脚本中处理多个 AJAX 结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5

CoffeeScript 总是以匿名函数返回
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)...
2024-04-20 前端开发问题
13