开发者

Looking for an AJAX jQuery way to get four field values and send them to server

I have an MVC application. I would like to get the values of a variable number of field values such as:

field_1, field_2 .. field_4

send them to my controller and then change the value of a Div's text based on the response. I never really used jQuery for anything like this. Do I need to use JSON to pack up the values and if so how do I unpack them on server. Is it something I can do easily? I hope for开发者_开发技巧 some advice.


I think,

you can find an answer at here. You should use the 'post' method for sending and receiving the data.

If you want to read more about JSON objects in different language read http://www.json.org


Assuming the inputs are in a from tag you can get the id of the form, serialize it, create an ajax request to the server, process it, then return data. It's look something like this.

function sendToServer() {
    var sendData = $('#myForm').serialize;
    $.get('/url/to/server/', sendData, function(returnData){
        //This is called on success
        $('#myDiv').html = returnData;
    });
}

Now this assumes also that the div has an id 'myDiv' and that returnData is already html formatted. It doesn't have to be you can do more processing inside the success call back

How to make the Ajax Call Jquery .get

How to serialize a form Jquery serialize


Brombombs answer is mostly complete. The '.serialize()' essentially takes the name of the html elements and the value and puts it into a JSON array structure. When you do a .get or a .post and have that data as the data to send, they will be available to PHP in global variables. .get the variables will be found in the $_GET variable and if doing a post, a $_POST variable.

for example

<form id="myForm">
<input name="firstName">John</input>
</form>

$('#myForm').serialize() returns a json { 'firstName' : 'John' }

and doing a .post... php can access this as

echo $_POST['firstName']; //prints John

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜