【问题标题】:passing variables to jQuery ajax success or error functions将变量传递给 jQuery ajax 成功或错误函数
【发布时间】:2012-06-26 10:17:49
【问题描述】:

我正在使用 JQuery $.ajax 循环访问一组 JSON URL 并将结果下载到一个数组中。一些 URL 返回 404 - 我正在处理并显示为 div 消息。

但是,我似乎无法传递 URL,更准确地说,它总是只传递数组中的最后一个 URL。

我认为这是因为 ajax 是异步的并且需要更长的时间才能完成,但我不确定如何确保只有当前的 JSON url(或变量)显示在 SUCCESS 或 ERROR 上

我的代码:

 // For every URL loop through 'baseitems' array
 for (var i = 0; i < baseitems.length; i++) {

  // This is where I'm hoping to store the current URL as a variable to pass to the end-user on Success or Error
  var caturl = baseURL + "/" + baseitems[i];

  // Get the data via JSON
  $.ajax({
    type: "GET",
    url: caturl,
    dataType: "json",
    async: true, // set so that the variables caturl get updated below
    success: function (result) {
        // Success: store the object into catalog array
        cat.unshift(result);
        $('#showdata').prepend("Loaded: " + caturl + "</br>");  // still buggy here - probably async JSON issue
    },
    error: function (xhr, textStatus, error) {
        // Error: write out error
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
        $('#showdata').prepend("ERROR : '" + error + "' trying to access: " + caturl + "</br>");  // still buggy here  - probably async JSON issue
    }
});

}

** 更新:工作代码**

带有@charlietfl帮助的完整工作代码+一些不错的东西,如成功/错误代码+加载的URL计数如下。感谢 charlietfl 和和事佬!

                $.ajax({
                    type: "GET",
                    url: caturl,
                    dataType: "json",
                    async: true, // set so that the variables caturl get updated below
                    beforeSend: function (jqXHR, settings) {
                        /* add url property and get value from settings (or from caturl)*/
                        jqXHR.url = settings.url;
                    },
                    success: function (result, textStatus, jqXHR) {
                        // Success: store the object into catalog array
                        var url = jqXHR.url;
                        cat.unshift(result);
                        $('#showdata').prepend("<font size=\"1\">Loading: " + url + " status: " + textStatus + "</font></br>");
                        successcount += 1;

                    },
                    /* error to be deprecated in jQuery 1.8 , superseded by "fail" */
                    error: function (jqXHR, textStatus, error) {
                        var url = jqXHR.url;
                        /* replace caturl with url in your append */
                        $('#showdata').prepend("<font size=\"1\" color=\"red\">ERROR : '" + error + "' trying to access: " + url + "</font></br>");
                    },
                    complete: function (jqXHR, textStatus) {
                        $('#showdata').prepend("<font size=\"3\">Loaded <b>" + successcount + "</b> of " + baseitems.length + " total catalogs.</font></br>")
                    }
                });

【问题讨论】:

  • 您是否尝试过在 ajax 调用中将 caturl 的值传递给 caturl 处的函数,然后将其传递回结果中?或者,由于您已经知道服务器上的 url,您将其传递回 ajax 成功 result 并在那里使用它

标签: jquery ajax json


【解决方案1】:

这是一种方法。 beforeSend 回调选项让您可以访问 jqXHR 对象和 ajax 设置对象。

您将无法在错误的追加中使用caturl,因为它不会与请求引发的错误同步。

  $.ajax({
    /* url, data ...& other opts*/
    beforeSend:function( jqXHR, settings){
        /* add url property and get value from settings (or from caturl)*/
         jqXHR.url= settings.url;
   },
   /* error to be deprecated in jQuery 1.8 , superseded by "fail" */
   error: function(jqXHR, , textStatus, error){
       var url=jqXHR.url;
     /* replace caturl with url in your append */ 
     $('#showdata').prepend("ERROR : '" + error + "' trying to access: " + url + "</br>");
   }

编辑:基于 3rd 方 API cmets,重要的是要认识到直接取自 $.ajax API

从远程服务器检索数据时(只能使用脚本或 jsonp 数据类型),永远不会触发错误回调和全局事件。

【讨论】:

  • 感谢您提供建议的代码。它为我指明了正确的方向,并通过一些小的调整得到了解决。
  • 我很好奇...是跨域调用..但是您收到错误触发?
  • 是的,错误触发正常 - 但是,我此时正在本地运行代码。请注意,它没有使用 JSONP(无回调函数),但似乎至少在本地工作
【解决方案2】:

我建议只从服务器传回 URL,在 pseduo-PHP 中是这样的:

function function_called_by_ajax()
{
    //processing...

    echo json_encode(array('urlString'=>$urlString));

}

现在在你的 ajax 成功中你可以得到字符串,类似于这个伪 js:

success: function (result) {
    var caturl = result.urlString;
    // Success: store the object into catalog array
    cat.unshift(result);
    $('#showdata').prepend("Loaded: " + caturl + "</br>");  
}

【讨论】:

  • 当 ajax 失败并且 OP 想要错误 url 时,很难从服务器传回 url
  • 我无法控制服务器并将 URL 从服务器传回。我正在阅读第 3 方 JSON API。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2011-01-25
  • 1970-01-01
  • 2012-03-02
  • 2011-01-18
  • 1970-01-01
相关资源
最近更新 更多