How to simulate a GET action and pass it to the same page without reload?
So, I'm making a site that gets data from a server (Names, with an autocomplete script), gathers it all up, then on submit is SUPPOSED to send the data gathered to the server to get a JSON string back for usage further down on the page.
However,开发者_开发技巧 said server does not have the last part and I need to simulate it. But I have no idea how.
Using HTML, JS, jQuery and nothing else.
So the question being, as the structure is there,
how do I get
<form action="Search" method="get">
<input type="hidden" name="foo"/>
<input type="hidden" name="bar"/>
<input id="submitButton" type="submit" value="Search"/>
</form>
Where foo and bar will have values at the time of submit,
to end up as a JSON object containing foo, bar and some random data I just make up,
in the .js, on pressing submit, WITHOUT reloading the page. (That is, pressing submit just kicks in the script and gives the form data to it but nothing else)
Edit: Sorry, changed post to get. The server will when working, respond to GET with JSON.
Put whatever JS array/object you expect back from the server in returnedData
:
$(function(){
var handleNewData = function(data){
alert('I got:\nfoo:'+data.foo+'\nbar:'+data.bar+'\nresults:'+data.results);
};
var reallySubmit = false;
$('form').submit(function(evt){
if (reallySubmit){
$.get(this.action,$(this).serialize(),handleNewData,'json');
}else{
// Put whatever spoof data you want here.
var returnedData = {
foo:this.elements.foo.value,
bar:this.elements.bar.value,
results:["jim", "jam", "jamboree"]
};
handleNewData( returnedData );
return evt.preventDefault();
}
});
});
See the working example here: http://jsfiddle.net/sQtkY/4/
Edit: Sorry, I forgot that jQuery will properly parse a JSON string for you if you pass the parameter. Updated the answer to show this; no need to stringify
your spoof values.
Edit 2: OK, one more update to show you how to include form values as well as spoof data.
Try this:
$("form").submit(function (event) {
event.preventDefault();
// NOTE: the following would work when the server is ready
//$.getJSON("http://whatever.com/endpoint.php", $(this).serialize(), function(data) {
// console.log(data);
//});
var fakeData = {
whatever: "data",
you: "need",
foo: "value",
bar: "value"
};
console.log(fakeData);
});
Make sure you have firebug open to see the console.log().
Try this
$("form").submit(function(event){
event.preventDefault();
$.post("http://whatever.com/post.php",$(this).serialize(), function(data){
alert(data);
});
});
精彩评论