【问题标题】:Access outer ajax parameter访问外部ajax参数
【发布时间】:2017-05-23 15:08:11
【问题描述】:

我有一个有 4 个参数的函数

function getToken(u, p, url, role) {
var that = this;
oururl = url;
$.ajax({
    type: 'GET',
    url: "/Base/getConfigUrl",
    success: function (data) {
        $.ajax({
            type: 'GET',
            async: false,
            url: url + '?username=' + u + '&password=' + p,
            success: 'callbackFunc',
            error : 'callbackError',
            contentType: "application/json",
            dataType: 'jsonp'
        });
    }

});

以及回调函数

function callbackFunc(resultData) {
// how to get the outer parameter
}

内部回调函数我需要访问角色参数我记录了this 变量,但我找不到任何东西

【问题讨论】:

  • “我记录了这个变量,但我什么也找不到”——this 与范围内的变量无关(除非它们也是全局变量(避免全局变量)并且你不使用严格模式(始终使用严格模式)。

标签: javascript ajax closures


【解决方案1】:

你不能,就其本身而言。 role 变量不存在于正确的范围内。

您需要重构您的代码,以便您可以从某个变量确实存在的地方获取该变量并将其传递给 callbackFunc 函数。

查看代码内嵌的 cmets 以了解所有更改的说明。

function callbackFunc(resultData, role) {
  // Edit the argument list above to accept the role as an additional argument
}


function getToken(u, p, url, role) {
  var that = this;
  var oururl = url; // Best practise: Make this a local variable. Avoid globals.
  $.ajax({
    type: 'GET',
    url: "/Base/getConfigUrl",
    success: function(data) {
      $.ajax({
        type: 'GET',
        // async: false, // Remove this. You are making a JSONP request. You can't make it synchronous. 
        url: url;
        data: { // Pass data using an object to let jQuery properly escape it. Don't mash it together into the URL with string concatenation. 
          username: u,
          password: p
        },
        success: function(data) { // Use a function, not a string
          callbackFunc(data, role); // Call your function here. Pass the role (and the data) as arguments.
        },
        error: function() {}, // Use a function, not a string
        // contentType: "application/json", // Remove this. You are making a JSONP request. You can't set a content type request header. There isn't a request body to describe the content type of anyway.
        dataType: 'jsonp'
      });
    }

  });

【讨论】:

  • 非常感谢您的提示,我无法让成功获得成功的功能,因为响应更像callbackFunc({"TokenValue" : "4f21wGAACBEJLyanR4JFZQmSBahNKck6OCAuH"})
  • 此答案中的代码将导致 jQuery 生成回调名称并将其包含在查询字符串中。任何体面的 JSONP 端点都会尊重这一点并在响应中使用该函数名称。如果没有,那么您可以使用 jsonp: false, jsonpCallback: "callbackFunc" 告诉 jQuery 使用先前定义的名称(您应该重命名您已经拥有的全局 callbackFunc,以便 jQuery 不会用成功函数覆盖它)。
  • 我确实尝试了那些 udpates,但是当它访问 callbackFunc 时,第二个参数未定义,即使参数数组仍然没有第二个参数。(我尝试了 jsonp: false, jsonpCallback: "callbackFunc" 但是它没有用)。我将使用任何存储来设置和获取抛出请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多