javascript - 访问ajax外部参数

标签 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
}

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

最佳答案

你本身不能。 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'
      });
    }

  });

关于javascript - 访问ajax外部参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138632/

相关文章:

java - 在 Java 中实现 "system"命令

javascript - 切换一个元素会禁用其他元素

javascript - 如何用 JavaScript 的内置函数替换此 JQuery Ajax 调用?

java - BGGA 闭包作为 java 的附加解决方案?

python - "Python closure"适用于函数对象吗?

javascript - 用于强制特殊标题格式的正则表达式

javascript - 如何检索 java Set 并迭代 ajax 调用响应中的值?

jquery - 更改选择时使用 jquery load 加载另一个选择选项

python - Python 中简单事物的类或闭包

javascript - 是否可以创建一个在 Javascript 中调用时表现得像函数的对象?