jQuery: Use of undefined constant data assumed 'data'
I am trying to use jQuery to make a synchronous AJAX post to a server, and get a JSON response back.
I want to set a javascript variable msg upon successful return
This is what my code looks like:
$(document).ready(function(){
$('#test').click(function(){
alert('called!');
jQuery.ajax({
async: false,
type: 'POST',
url: 'http://www.example.com',
data: 'id1=1&id2=2,&id3=3',
dataType: 'json',
success: function(data){ msg = data.msg; },
error: function(xrq, status, et){alert('foobar\'d!');}
});
});
[Edit]
I was accidentally mixing PHP and Javascript in my previous xode (now corrected). However, I now get this even more cryptic error message:
uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js :: anonymous :: line 19"开发者_高级运维 data: no]
What the ... ?
In your success
callback, you are mixing Javascript and PHP code ; which is probably not quite what you want to do.
You must be aware that :
- PHP is executed on the server-side ; for .php files
- Javascript is executed on the client-side (browser)
The function hooked on the success
callback will only be executed on the client-side, where there is no PHP execution ; and it will receive the data sent by the PHP script on the server-side (The one receiving the Ajax request).
The data
as received by the function hooked on success
is a Javascript object.
Which means that, here, you might want to use something like this :
success: function(data){ msg = data.msg; },
i.e. no PHP code here.
Edit after the comment + edit of the OP
You are getting a "NS_ERROR_ILLEGAL_VALUE nsIXMLHttpRequest.open
" error ; which means, I suppose, that you are passing some kind of illegal URL to the Ajax request.
Are you sure that the URL you're passing to jQuery.ajax
is a valid one ?
For instance :
- It should not be empty
- It should point to an URL that's on the same domain-name as your application
The string your are attempting to output is not quoted. Try:
success: function(data){ msg = <?php echo "data.msg;"; ?> },
I don't really see the point, why not just do:
success: function(data){ msg = data.msg },
精彩评论