简体   繁体   中英

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. My data.php code is working but javascript code is not working so please help me.

Javascript code

dataString = 'no='+ no; 

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

        console.log(response);
  });

php code

$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 ).
Try printing out the error by using error which is called when no valid JSON is received -

$.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.

EDIT
This edit is assuming that he php response is invalid JSON as observed from the comments.
Looking at your php code, you have used this -

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

Try this instead -

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

EDIT 2
Looking at your php code again, there seems to be an error while printing -

echo result;

It should be -

echo $result;

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

You should $_GET in your php code or change code like this :

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

    console.log(response);
  });

In php use,

$no=$_REQUEST['no'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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