使用AJAX将变量传递给PHP并再次使用AJAX检索它们

我想将值传递给PHP脚本,所以我使用AJAX传递它们,并且在同一个函数中我使用另一个AJAX来检索这些值。

问题是第二个AJAX没有从PHP文件中检索任何值。 为什么是这样? 如何将传递给PHP脚本的变量存储起来,以便第二个AJAX可以检索它?

我的代码如下:

AJAX代码:

$(document).ready(function() { $("#raaagh").click(function(){ $.ajax({ url: 'ajax.php', //This is the current doc type: "POST", data: ({name: 145}), success: function(data){ console.log(data); } }); $.ajax({ url:'ajax.php', data:"", dataType:'json', success:function(data1){ var y1=data1; console.log(data1); } }); }); }); 

PHP代码:

  

对于json数据,请使用dataType:"json"

 $.ajax({ url: 'ajax.php', //This is the current doc type: "POST", dataType:'json', // add json datatype to get json data: ({name: 145}), success: function(data){ console.log(data); } }); 

阅读文档http://api.jquery.com/jQuery.ajax/

还有PHP

  where color='".$userAnswer."'" ; $result=mysql_query($sql); $row=mysql_fetch_array($result); // for first row only and suppose table having data echo json_encode($row); // pass array in json_encode ?> 

不需要使用第二个ajax函数,你可以在函数内取回成功,这里的另一个问题是你不知道第一个ajax调用何时完成,那么,即使你使用SESSION你可能也不会在第二个AJAX中得到它呼叫。

所以,我建议使用一个AJAX调用并获得成功的价值。

例如:在第一个ajax调用中

  $.ajax({ url: 'ajax.php', //This is the current doc type: "POST", data: ({name: 145}), success: function(data){ console.log(data); alert(data); //or if the data is JSON var jdata = jQuery.parseJSON(data); } }); 
 $(document).ready(function() { $("#raaagh").click(function() { $.ajax({ url: 'ajax.php', //This is the current doc type: "POST", data: ({name: 145}), success: function(data) { console.log(data); $.ajax({ url:'ajax.php', data: data, dataType:'json', success:function(data1) { var y1=data1; console.log(data1); } }); } }); }); }); 

像这样使用,首先进行ajax调用以获取数据,然后你的php函数将返回你将获得数据的结果并将该数据传递给新的ajax调用

你必须用单引号传递值

 $(document).ready(function() { $("#raaagh").click(function(){ $.ajax({ url: 'ajax.php', //This is the current doc type: "POST", data: ({name: '145'}), //variables should be pass like this success: function(data){ console.log(data); } }); $.ajax({ url:'ajax.php', data:"", dataType:'json', success:function(data1){ var y1=data1; console.log(data1); } }); }); }); 

尝试它可能会工作…….

在您的PhP文件中,将会有一个名为$_REQUEST的变量,它包含一个数组,其中所有数据都使用AJAX从Javascript发送到PhP。

试试这个: var_dump($_REQUEST); 并检查您是否收到了这些值。