jQuery .Ajax() function selector , store specific data in variable
I am new to jQuery and I have the following problem.
My开发者_Go百科 project has say 2 pages, 1.JSP and 2.html. Now I want to pick selected data from 2.html and use it on 1.JSP. Now this was achieved very easily using .load
but I want the data to be present in a JavaScript variable rather than put it on the page (div tags, etc.), so that I can work upon that data (modify or add to database).
I tried using .ajax
and was able to write the following code:
var value = (function () {
var val = nulll;
var filename = " 2.html";
$.ajax ({
'async': false,
'global': false,
'url': filename,
'success' : function(data) {
val = data;
}
})
return val;
})()
document.write(value)
Where do I put the selector format (say div.id5) so that my variable have only relevant data rather than the full file data?
function modify_data(data){
....
}
$.ajax({
type: "POST", //POST OR GET
url: "1.JSP", // URL TO SEND AJAX DATA TO
data: "name=John&location=Boston", // DATA TO SEND
success: function(data){ // CALLBACK FUNCTION
modify_data(data);// sending data to another function to play with it
$('body').html(data);
}
});
This is how to send an Ajax request and print it on the body after modifying the received data.
Let's say you have 1.html and 2.html, and inside 2.html's body you have this:
<body>
<h1 id="foo">hello</h1>
</body>
Then in your 1.html you'd get the text inside H1 like this:
var filename = " 2.html";
$.ajax ({
'async': false,
'global': false,
'url': filename,
'success' : function(data) {
var html = $(data);
html.each(function() {
if(this.tagName && this.tagName == 'H1') {
alert( $(this).html() );
}
})
}
})
This should give an annoying JS alert with 'hello' written inside it.
I guess you're referring to $.load() function's ability to receive a jquery selector along with the URL to filter the result. That's to say, today you're doing it like this:
$('div').load('2.html div.id5');
So you really want to be able to do the same using the $.ajax() function. I believe the easiest way for you to do that is to use the .find() jquery function inside your 'success' event function (I'm omitting the whole .ajax() call, just typing the success event code):
success: function (data) {
val = $(data).find('div.id5').html();
// now you ony have that specific div's contents
}
I saw a few other errors in your javascript code I think you'll want to fix (if you're actually using that code).
// null is defined with 2 ls
var val = nulll;
// Is the space on purpose?
var filename = " 2.html";
精彩评论