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

不想你离开。 提交于 2021-01-27 06:53:09

问题


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)

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.

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


回答1:


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

PHP

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

Javascript/jQuery

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

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



回答2:


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

$data = array();

$data[] = $person1;

$data[] = $person2;

echo json_encode($data);


来源:https://stackoverflow.com/questions/20437603/how-to-get-multiple-responses-to-a-single-ajax-request-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!