javascript 如何在php中获得对单个ajax请求的多个响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20437603/
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-10-27 18:29:17  来源:igfitidea点击:

How to get multiple responses to a single ajax request in php

javascriptphpajax

提问by goodbytes

I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)

我正在制作一个网络应用程序,我想在其中提供搜索功能。我正在发送带有 ajax 请求的搜索名称,我想提取该特定人员的记录。但由于要显示的细节很多,我发现很难得到回应。(我一次无法收到多个回复)

I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.

我想知道,是否有办法为单个请求获得多个响应,或者是否有办法将目标 PHP 文件中的所有变量作为数组或其他东西发送到请求的 javascript 文件。

Thank you. If this question is asked before, please provide the link.

谢谢你。如果之前问过这个问题,请提供链接。

回答by deadlock

Use JSONas the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:

使用JSON作为数据类型在PHP(后端)和Javascript(前端)之间进行通信。例子:

PHP

PHP

<? 
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>

Javascript/jQuery

Javascript/jQuery

$.ajax({
  url: "your_script.php",
  dataType: "JSON"

}).success(function(person) {
  alert(person.name) //alerts Jon Skeet
});

回答by ma?ek

Add everything you want to an array, then call json_encodeon it.

将您想要的所有内容添加到数组中,然后调用json_encode它。

$data = array();

$data[] = $person1;

$data[] = $person2;

echo json_encode($data);