使用 jQuery AJAX 从 PHP 返回多个返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4594265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:37:16  来源:igfitidea点击:

multiple return values from PHP with jQuery AJAX

phpjqueryajaxreturn-value

提问by benhowdle89

I'm using this jQuery code:

我正在使用这个 jQuery 代码:

$.ajax
({
    type: "POST",
    url: "customerfilter.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
        $(".custName").html(html);
    }
});

How can i do something like this: $(".projDesc").html(html1); So i can split the returned results into two html elements?

我该怎么做:$(".projDesc").html(html1); 所以我可以将返回的结果分成两个 html 元素?

echo "<p>" .$row['cust_name']. "</p>";

thats the PHP i'm using and i want to echo another statement which i can put into another HTML element

这就是我正在使用的 PHP,我想回应另一个我可以放入另一个 HTML 元素的语句

Does this make sense?

这有意义吗?

回答by Klemen Slavi?

Use json_encode()to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.

使用json_encode()从PHP关联数组转换成JSON和使用$.getJSON(),它会返回一个Javascript数组。

Example:

例子:

<?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?>

In Javascript:

在 JavaScript 中:

$.getJSON("myscript.php", function(data) {
  alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});

回答by Jake N

Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:

使您的响应返回 JSON,您需要将 jQuery 更改为此,因此预期的数据类型为 json:

$.ajax
({
    type: "POST",
    url: "customerfilter.php",
    dataType: 'json',
    cache: false,
    success: function(data)
    {
        $(".custName").html(data.message1);
        $(".custName2").html(data.message2);
    }
});

Then you need to encode your response as a JSON Array:

然后您需要将您的响应编码为 JSON 数组:

 <?php echo json_encode(
      array("message1" => "Hi", 
      "message2" => "Something else")
 ) ?>

回答by Thariama

Why don't you return a JSONobject. This way you can easily put many different results inside the ajax response.

为什么不返回一个JSON对象。通过这种方式,您可以轻松地将许多不同的结果放入 ajax 响应中。