简体   繁体   English

如何使用getJson将变量发送到php文件

[英]How to use getJson to send variable to php file

Here is the javascript code that has a "no" in the datastring and i want to pass that datastring to data.php using getJson So that in the end i can get json as a response. 这是在数据字符串中具有“ no”的javascript代码,我想使用getJson将该数据字符串传递给data.php,以便最终我可以得到json作为响应。 My data.php code is working but javascript code is not working so please help me. 我的data.php代码正常工作,但是javascript代码无效,因此请帮助我。

Javascript code JavaScript代码

dataString = 'no='+ no; 

$.getJSON("data.php", dataString,function(response){

        console.log(response);
  });

php code PHP代码

$no=$_POST['no'];

$headers = array(
'Content-Type: application/json',
);

$url = 'https://www.outpan.com/api/get-product.php?barcode='.$no.'&apikey=318c91a99b132a29dda536d63e7fb8b4';


$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, false);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );


curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);




 $result = curl_exec($ch);



curl_close($ch);

//$result_arr = json_decode($result, true);

echo result;

One possibility is response is not valid JSON (I am not sure, since you seemed to have tried printing the json_decoded version ). 一种可能是响应不是有效的JSON(我不确定,因为您似乎已尝试打印json_decoded version )。
Try printing out the error by using error which is called when no valid JSON is received - 尝试使用打印出的错误error没有接收到有效的JSON时调用-

$.getJSON("data.php", dataString,function(response){
    console.log(response)
}).error(function(jqXHR, textStatus, errorThrown){ 
    console.log(textStatus+" - "+errorThrown); 
}); 

If an error is logged, then checkout the curl response in php and make sure it is valid json. 如果记录了错误,则在php中检查curl响应,并确保它是有效的json。

EDIT 编辑
This edit is assuming that he php response is invalid JSON as observed from the comments. 从评论中可以看出,此编辑假定php响应是无效的JSON。
Looking at your php code, you have used this - 查看您的php代码,您已经使用过-

$headers = array(
'Content-Type: application/json',
);

Try this instead - 试试这个-

header('Content-Type: application/json');

EDIT 2 编辑2
Looking at your php code again, there seems to be an error while printing - 再次查看您的php代码,打印时似乎出现了错误-

echo result;

It should be - 它应该是 -

echo $result;

使用$ _GET在您的php代码中,您现在正在使用$ _POST

You should $_GET in your php code or change code like this : 您应该在PHP代码中使用$ _GET或更改代码,如下所示:

$.getJSON("data.php", { no: no },function(response){

    console.log(response);
  });

In php use, 在php中使用

$no=$_REQUEST['no'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM