jQuery ajax请求:如何在成功函数中访问发送的数据?

Xri*_*ter 7 javascript ajax jquery

所以我试图实现以下目标,但我无法弄清楚如何使这项工作.

$.ajax({
  url: "whatever.php",
  method: "POST",
  data: { myVar: "hello" },
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+data.myVar); // <<<< data.myVar is not accessible from here
    console.log('the value of myVar was: '+myVar); // <<<< myVar is not accessible from here
  }
});
Run Code Online (Sandbox Code Playgroud)

是否有访问的价值方式myVar.success()功能?我可以以某种方式获取data在此.success()函数中在此ajax请求中发送的原始对象吗?

希望你的解决方案.谢谢!

Sea*_*dle 7

除了 Piyin 之外,所有其他答案都是不可靠的并且是不好的做法。

AJAX 请求本质上是异步的。这意味着当响应从服务器返回时,它们设置的变量可能已更改。如果您想要一个示例,只需制作两个按钮,它们都触发相同的代码,但设置myData为不同的值,然后在响应返回之前快速单击它们......现在变量已更改,您将得到不可靠的结果。

Piyin的答案也很好,但有时你会得到不同格式的发送数据。它可能是一个已被解析的 JSON 对象stringify,也可能是带有查询字符串的 GET 格式,等等。

对编码器来说最简单的方法(尽管它确实在 RAM 中产生了更多的开销)是分配 AJAX 对象的新属性并在回调中访问它,如下所示(使用 Piyin 的示例):

var dataToSend = { myVar: "hello" };
$.ajax({
  url: "whatever.php",
  method: "POST",
  data: dataToSend,
  sentData: dataToSend, //add this property
  success: function(response) {
    console.log('received this response: ' + response);
    console.log('the value of myVar was: '+ this.sentData.myVar); //access sentData property
  }
});
Run Code Online (Sandbox Code Playgroud)


Piy*_*yin 6

您可以使用this访问整个对象。所以你可以做这样的事情:

$.ajax({
  url: "whatever.php",
  method: "POST",
  data: { myVar: "hello" },
  success: function(response) {
    console.log('received this response: '+response);
    console.log('the value of myVar was: '+this.data.myVar);
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 0

一般来说,如果您希望能够多次引用数据,则需要确保它在正确的范围内。您在内部传递的 json 数据对象的范围.ajax()是 ajax 函数。如果您希望能够引用data:外部的值,例如您调用的范围 .ajax()最简单的方法是将其分配给变量。例如

myData = { myVar: "hello" };
$.ajax({
  url: "whatever.php",
  method: "POST",
  data: myData,
  success: function(response) {
    console.log('received this response: '+response);
    $("#response").html(response);
    console.log('the value of myVar was: '+myData.myVar); // <<<< data.myVar is not accessible from here
    $("#myVar").html(myData.myVar);
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="response"></p>
<p id="myVar"></p>
Run Code Online (Sandbox Code Playgroud)

  • 当时我不明白的一件事是:json `data` 对象位于 `.ajax()` 范围内。`.success()` 函数也是 `.ajax()` 作用域**,对吧?那么为什么我无法在 .success() 函数中访问 data 对象呢? (2认同)