javascript - getJSON in jquery & json_encode in PHP & headers -


i have php file(courses.php) in separate domain.

<?php header('content-type: application/javascript; charset=utf-8');   $array = array();  $array[0]["id"] = "1";  $array[1]["id"] = "2";  $array[2]["id"] = "3";   $array[0]["coursename"] = "course name 1";  $array[1]["coursename"] = "course name 2";  $array[2]["coursename"] = "course name 3";   echo json_encode($array);  ?> 

i use jsonp access data below in localhost.

$.getjson( 'http://example.info/mobile/courses.php?callback=?', function( result ) {        console.log(result); }); 

it not work. if change url twitter below works

$.getjson( 'http://search.twitter.com/search.json?q=dogs&callback=?', function( result ) {        console.log(result); }); 

according knowledge should courses.php file. have no clue how fix this.

what issue? how can fix this?

your script not return jsonp, json. response jsonp javascript "file" 1 function call, function name comes callback parameter.

so instead of returning

{"bar": 42} 

you have return

foo({"bar": 42}); 

include function name in output:

echo $_get['callback'] . '(' . json_encode($array) . ');'; 

you want use sensible default if $_get['callback'] not present, or return json then. useful if don't need or can use jsonp (e.g. calling url server side script).


note: name "jsonp" bit misleading, because technique not have json. response generate pure javascript code , pass function call, not have json-encoded-and-as-object-interpreted data structure (it can valid javascript data type).


Comments