繁体   English   中英

如何通过$ .ajax调用使用成功函数

[英]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-Typeapplication/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM