访问外部ajax参数

时间:2017-05-23 15:08:12

标签: javascript ajax closures

我有一个带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变量,我找不到任何东西

1 个答案:

答案 0 :(得分:1)

你本身不能。 role变量不存在于正确的范围内。

您需要重构代码,以便可以从存在的位置获取变量并将其传递给callbackFunc函数。

请参阅与代码内联的注释,以获取对所有更改的解释。

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'
      });
    }

  });