[英]jquery ajax call success, how do I change a global variable in the wrapper javascript function?
[英]how do i use the success function with an $.ajax call
我不明白成功函数在jquery的$ .ajax调用中如何工作。
例如
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
如何在成功功能中使用该数据? 似乎没有地方可以解释数据参数是什么,他们似乎模棱两可。
另一个问题是,数据:“ function = 1”是否与作为成功函数参数的数据相关?
data
参数的内容取决于响应的类型。 如果Content-Type
为application/json
,则将其解析为JSON。 如果是text/html
或类似内容,则内容为HTML。 就您而言,您似乎正在返回文本。 如果您将Content-Type
标头设置为text/plain
或类似text/plain
,则data
应仅为字符串。
为了回答您的第二个问题,Ajax请求的data
属性有所不同。 它指定了发送的请求数据。 换句话说,如果有GET
请求,则为查询字符串;如果为POST
请求,则为post“ form”变量。
data
变量包含php文件的输出,因此,如果在php文件中,则可以执行以下操作:
echo "<p>success</p>";
data
将包含<p>success</p>
。
在您的示例中,您将php文件更改为:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
data
就是服务器端脚本返回的内容,因此在这种情况下
this is the data i want to return and use
提供满足if()
条件的条件。
没人真正说出data
包含什么内容,因为尽管它总是一个字符串,但它可以包含各种不同的东西。 有时是HTML,有时是JSON,有时只是返回消息。
在您的情况下, data
将只是一个字符串, 只要您在服务器端脚本中回显该字符串即可 。
最简单的方法是将数据加载到某个占位符元素(div?)EG中
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.