Trying to get a very simple request working with MooTools Request.JSON. After having no success building it from scratch, I took an example from somewhere and slowly pared it down to the bare, bare minimum, then put it back into my own page. The only things changed are the url and element ID, but to no avail.
Any help, ideas, will be greatly appreciated.
json.php
<?php
$result['name'] = 'yay';
header('Content-type: application/json');
echo json_encode($result);
?>
demo.js (snippet inside window.addEvent('domready', function() { )
$(document.body).getElement('input[id=game_name]').addEvents({
'keydown' : function(){
alert('hmm'); //this fires
var jsonRequest = new Request.JSON({
url: "json.php",
onComplete: function(result){ //changing to onSuccess kills everything afterwards
alert('result.name'); //this fires
alert(result.name); //this does not fire
alert('result.name'); //this does not fire
}
}).get();
}
});
PS. in neither my page, or the par开发者_C百科ed down example pages, can i get the request to send on domready, only inside an event. why is that?
thanks again
As it turns out, the problem was that I had accidentally loaded a synced duplicate file into my browser that was therefore (obviously) unable to execute anything server side.
Thank you very much for your help.
Several suggestions/questions:
Are you getting any errors in your web browser's console? Which web browser are you using? The fact that the third alert doesn't fire at all suggests that
alert(result.name);
is throwing an error, in which case, all further execution will be stopped and an error will appear on your browser's console.When you say "changing to onSuccess kills everything afterwards", what exactly do you mean? Does code further down (i.e. code that's not included in the above code snippet) never execute? Or does
onSuccess
just never fire?Is
json.php
in the same directory as the page where this script is running? Try replacingjson.php
inurl: "json.php"
with an absolute URL (/mydirectory/json.php
orhttp://www.mywebsite.com/mydirectory/json.php
) and see whether this works.
If it's any help, the following code results in an alert reading "yay" (running on a local server; json.php
is a file containing the PHP code in your question):
var jsonRequest = new Request.JSON({
url: "json.php",
onSuccess: function(result) {
alert(result.name);
}
}).get();
you can find a great tutorial here
http://net.tutsplus.com/tutorials/javascript-ajax/checking-username-availability-with-mootools-and-request-json/
Exactly the same problem here. I solved it by decoding the JSON string, which is given as parameter (instead of the expected object).
onSuccess: function(jsonString) {
console.log(JSON.decode(jsonString));
}
Here ist the documentation: http://mootools.net/docs/core/Utilities/JSON#JSON:decode
精彩评论