简体   繁体   English

使用jquery,发布一些json数据并处理返回的json响应的最简单函数是什么?

[英]Using jquery, what is the simplest function to post some json data and process a returned json response?

When users click on an element in my webpage, I would like to call a javascript function that reads the values of a few text boxes on the page, wraps their contents as json where the keys are the ids for the text boxes and the values are the contents of each text box, and then posts the resulting json to a url. 当用户单击我网页中的元素时,我想调用一个javascript函数,该函数读取页面上几个文本框的值,将其内容包装为json,其中键是文本框的id,而值是每个文本框的内容,然后将生成的json发布到url。

I would then like the same function to expect back a json response and call another javascript function with the returned json data. 然后,我希望同一个函数能够返回一个json响应,并使用返回的json数据调用另一个javascript函数。

Question: What is the best way to write the javascript function to create a json structure from html elements, post the json with jquery, and call another javascript function with the resulting json response from the server? 问题:编写javascript函数以从html元素创建json结构,使用jQuery发布json以及使用来自服务器的json响应调用另一个javascript函数的最佳方法是什么?

There are some json related options in $.ajax() $.ajax()有一些与json相关的选项

Check them out: http://api.jquery.com/jQuery.ajax/ 签出它们: http : //api.jquery.com/jQuery.ajax/

You can use json2 to marshall the data to json format and send it using ajax. 您可以使用json2将数据编组为json格式,然后使用ajax发送。 Once you got the response back, you can use the result to call other javascript in your success callback. 收到响应后,就可以使用结果在成功回调中调用其他javascript。 I would recommend using a decent javascript framework for ajax calls to make things a little bit easy. 我建议对ajax调用使用一个体面的javascript框架,以使事情变得容易一些。

I use malsup's jQuery form plugin. 我使用malsup的jQuery表单插件。 http://malsup.com/jquery/form/ http://malsup.com/jquery/form/

As he says himself "The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX." 正如他自己说的那样:“ jQuery表单插件允许您轻松,毫不费力地升级HTML表单以使用AJAX。”

Check out this question: How can I post an array of string to ASP.NET MVC Controller without a form? 看看这个问题: 如何在没有表单的情况下将字符串数组发布到ASP.NET MVC Controller?

The accepted answer is pretty simple. 接受的答案非常简单。 But to make it even more simple, make postData a string, and have the SaveList method take in a single string. 但是,为了使其更加简单,请将postData设置为字符串,并让SaveList方法采用单个字符串。 I just tried it and it works. 我刚试过,它起作用。 Just a single statement on each the client and the server! 在每个客户端和服务器上只有一个语句!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM