如何从JQuery Ajax请求中获取“数据”

这是我在index.html上的代码:

  TODO supply a title     $.ajax({ type: "POST", url: 'test.php', data: "check", success: function(data){ alert(data); } });    

如何编写test.php以获取在AJAX API中发送的“数据”?

你在这里问一个非常基本的问题。 您应该首先阅读一些Ajax教程。 只是为了帮助你一点(假设你知道发送数据的GET和POST方法),数据中的“数据”:“检查”与function(数据)中的“数据”不同。 为清楚起见,您应将它们命名为不同,如下所示:

 $.ajax({ type: "POST", url: 'test.php', data: "check", success: function(response){ alert(response); } }); 

这清楚地表明,一个是您在POST参数中发送到test.php文件的数据,另一个是您在运行后从test.php文件获取的响应。 实际上,你POST到test.php的数据参数必须是像这里的哈希(我在这里假设键为“type”:

 $.ajax({ type: "POST", url: 'test.php', data: {"type":"check"}, success: function(response){ alert(response); } }); 

显然,数据中可能存在更多的键 – 值对。

所以,假设你的test.php文件是这样的:

 if(isset($_POST['type'])){ //Do something echo "The type you posted is ".$_POST['type']; } 

在这种情况下,您的警报应显示为:“您发布的类型是检查”。 这将根据您在AJAX调用中为“type”键发送的值而更改。

你可以这样试试

  $.ajax({ type: "POST", url: 'test.php', data: {"data":"check"}, success: function(data){ alert(data);//This will alert Success which is sent as the response to the ajax from the server } }); 

在test.php中

 if(isset($_POST['data']) && $_POST['data'] == 'check'){ //$_POST['data'] contain the value that you sent via ajax //Do something echo 'Success'; } 

您可以查看更多内容

如果你想用jquery ajax处理更多的数据。 我更喜欢json数据类型。

简单地使用就像这样。

 $.ajax({ type: "POST", url: 'test.php', dataType: 'json', data: {"data":"check"}, success: function(data){ alert(data.value1); alert(data.value2); } }); 

在您的PHP代码中

 if(isset($_POST['data']) && $_POST['data'] == 'check'){ //Data 1 $data['value1'] = 'Data 1 Got Successfully'; //Data 2 $data['value2'] = 'Data 2 Got Successfully'; $resonse = json_encode($data); echo $response; } 

你的HTML会是

   TODO supply a title       

请注意,数据是一个数组,因此您必须在数据中传递变量及其值。 您可以在数据中传递多个变量,用逗号分隔它们。

并在test.php中选择ajax发送的数据:

  

$ _POST取决于AJAX调用中使用的类型。 如果type是GET,那么在PHP中它将是$ _GET。 一个简单的事情是$ _REQUEST,无论AJAX调用是GET类型还是POST类型。

 $.ajax({//create an ajax request to load_page.php type: "POST", url: "test.php", data:{"data":"check"}, success: function(data) { if (data) { alert(data); } else { alert('Successfully not posted.'); } } }); 

在test.php中

  

PHP文件的输出将发送到您的AJAX succes函数。