jQuery getJSON function with alert not working
I am trying to get the jquery getJSON function to work. The following seems very simple yet it doesn't work.
$("#edit-item-btn").live('click', function() {
var name = this.id;
$.getJSON("InfoRetrieve",
开发者_开发问答 { theName : name },
function(data) {
alert(name);
});
});
- Make sure the surrounding code is working with your DOM by replacing the
getJSON
call with a simplealert
- Make sure the "InfoRetrieve" path actually exists. If you replace your file name in the URL bar with InfoRetrieve does it return
JSON
? function(data)
needs to be closed with a}
before you close the click handler.{ theName : theName }
makes more sense to me as thedata
. Are you sure you entered that right?
You are using name
variable on two places, but this variable is never defined.
Shouldn't you be doing alert(data)?
Have you tried using Firebug or Chrome Developer Tools to see what requests are being made?
Does a file called InfoRetrieve
exist in the current path of your site? What does it return?
I'm not convinced your code is correct. Try this and see what happens:
$("#edit-item-btn").live('click', function() {
var name = this.id;
$.getJSON("InfoRetrieve",
{ theName : name },
function(data) {
alert(data.name);
});
});
This should work if InfoRetrieve responds with a JSON string like this:
{"name":"Sally Smith"}
A few things to note:
- You are sending a request to ./InfoRetrieve in the same directory as the page is located. If you are using a servlet, is that actually correct? Or do you want "/servlet/InfoRequest"?
- You are sending data as input to InfoRetrieve with a key of "theName" and a value of whatever is "this.id" is. Does your servlet know how to accept this input?
- You are then receiving back a response from InfoRetrieve, and "data" is set to an object that represents the json in the response. You need to then access properties of data to get at values in the response.
精彩评论