简体   繁体   中英

Ajax Request for JSON Data

I try to request the following JSON Data:

 {"status":"success","id":8,"title":"Test","content":"dies ist test 12"}

With this Ajax Request:

$.ajax({
url: 'http://www.XXX.de/?apikey=XXX&search=test',
type: "GET",
dataType: 'jsonp',
success: function(data){
$('#content_test').append(data.content);
 },
 error: function(data){
 //
 }
});

It is not working. What I'm doing wrong?

Here is an example on how to use jsonp

$.ajax({
    url: 'http://www.XXX.de/?apikey=XXX&search=test',
    type: 'GET',        
    dataType: 'jsonp',
    jsonp: '$callback',
    success: function(data) {
        console.log(data);
        $('#content_test').append(data.content);
    },
    error: function(err) {
        console.log(err);
    }
});

Also open your development tool (Ctrl + Shift + J) and check if you have any errors in your console output.

My Solution::

To get the data it is necessary to have a correct callback like this in the PHP file of WP:

$callback = $_GET['callback'];
$response = json_encode( $return );

if ( ! empty ($callback)){
echo $callback . '(' . $response . ')';
} else {
echo $response;
}

die;

Ajax:

 $.ajax({
 url: 'http://www.XXX.de/?apikey=XXX&search=test&callback=?',
 type: "GET",
 dataType: 'json',
 success: function(data){
 $('#content_test').append(data.content);
  },
  error: function(data){
  //
  }
 });

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