问题
I am trying to make a simple JSONP call to get a json file which is loaded on the remote server.
Here is my simple json file loaded on the server.
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
My Controller code which calls this file to get the data
Ext.data.JsonP.request(
{
url : 'http://xx.xx:8080/ThemeSelector.json',
callback : 'someCallback' ,
someCallback: function(success, result) {
var text = result.responseText;
var object = Ext.decode(text);
themeName = object['homePage'][0].themename;
}
});
I am getting the error "Uncaught SyntaxError: Unexpected token : "
I know that the response should be wrapped in the object but not able to make the exact correction in json file and my code. Any help please?
Thanks
回答1:
JSONP requires that the response be in the form of a JavaScript function call, passing the actual JSON object as the parameter. Plain JSON won't (can't) work.
The exact details of how the function call should look (in particular, the function name) can vary, but usually it's a parameter added to the HTTP request. The server should construct the response based on that parameter's value.
回答2:
To work with JsonP, your json response should contain the callback
parameter you've sent. Without that, callback
function will not get called and produces error since it does require that. In your case, you just have plain JSON file on server to serve. So you cant use JsonP directly with this file.
If you've some control over server, then you can write a script that can do this for you like -
<?php
header('Content-Type: text/javascript');
$response = file_get_contents('ThemeSelector.json');
echo $_GET['someCallback'] . '(' . $response .' );';
?>
Then received json response will look something like -
Ext.data.JsonP.callback2 (
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
)
来源:https://stackoverflow.com/questions/14864753/sencha-touch-how-to-get-the-simple-json-file-as-response-using-jsonp