猿问

将变量从javascript传递到php文件

我已经开发了API(zomato),可为我提供餐厅的详细信息。我想将它们插入我的本地数据库,但是在将变量传递给PHP时遇到了问题,因为$ _GET无法处理该变量。我尝试使用$ _POST,但帖子的输出为空。


// JS代码


function showCafes(str){

     var xhttp;

  xhttp = new XMLHttpRequest();

  console.log(str);

  xhttp.open("GET","https://developers.zomato.com/api/v2.1/search?entity_type=city&q=t&start="+str+"&count=20" , true);

  xhttp.send();

  var restaurants="";

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

        var r=JSON.parse(this.responseText);

 var rest ={

      name : r.restaurant[1].restaurant.name

     };

    $.post("addFromApi.php", rest);

     window.location.href="addFromApi.php";

// PHP代码


<?php 

print_r($_POST);

?>

我期望从PHP代码中打印其中第一个元素的名称。//来自API的示例输出


{"results_found":1,

"results_start":0,

"results_shown":1,

"restaurants":

[{"restaurant":{

"R":{"res_id":18692654},

"id":"18692654",

"name":"East Village"}


长风秋雁
浏览 187回答 1
1回答

慕的地6264312

我已经通过像这样从js制作表格来解决了这个问题&nbsp; &nbsp; &nbsp;document.getElementById("cafes").innerHTML += '<form id="rests" action="addFromApi.php" method="post"><input type="hidden" name="q" value="'+restaurants+'"></form>';document.getElementById("rests").submit();//resturants is the variable that I wanted to pass to php.
随时随地看视频慕课网APP
我要回答