jquery $.post - json - 发送/接收输入数据的正确方法(仅在客户端) - 两个问题的探索

发布于 2024-09-15 09:48:14 字数 467 浏览 5 评论 0原文

让我们想象一下我们有这样的东西:

$.post('somescript.php', 'WHAT CAN WE PUT HERE?',
        function(replyData) {

1) 默认情况下,$.POST方法的第三个参数会正确读取XMLResponse响应吗? 那么,为什么我们需要这个参数 'replyData' ?我们产生这种争论的原因是什么?

2) 第二个参数接受将要发送的数据。好的。 我想使用 json,但是,我不确定是否应该在第二个参数上使用 json 格式 定位将包含该数据的输入表单字段?

附加说明: 数据将来自输入字段,我需要通过 $.POST ajax 请求将其发送到服务器。我打算使用 json 编码和 json 解码 php 函数。

提前致谢, MEM

Let's imagine that we have something like:

$.post('somescript.php', 'WHAT CAN WE PUT HERE?',
        function(replyData) {

1)
By default, the third argument of $.POST method, will read the XMLResponse response correct?
So, why do we need that argument 'replyData' ? What are the reasons that we may have for having that argument?

2)
The second argument accepts the data that will be sent. Ok.
I would like to use json, however, I'm not sure if I should use a json format on that second argument or target the input form field that will contain that data?

Additional notes:
The data will come from a input field, and I need to send it via an $.POST ajax request to the server. I intend to use json encode and json decode php functions.

Thanks in advance,
MEM

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

dawn曙光 2024-09-22 09:48:14

replyData 参数包含服务器返回的响应正文,然后您可以对其进行操作以将其显示在页面上、验证服务器端是否成功处理数据等。您没有使用它(例如,如果您不返回任何数据)。

您提供的数据(JSON 格式)仍然需要采用查询字符串的形式,例如 param=value。该值还需要使用 encodeURIComponent() 进行正确编码

$.post('somescript.php', 'data='+encodeURIComponent(myJSON),
    function(replyData) {

然后,您可以通过 $_POST 超级全局访问 PHP 脚本中的 JSON:

$data = json_decode($_POST['data']);

但是,对于简单的输入字段来说,JSON 有点过大了。使用 JSON 代替表单字段的名称/值对的情况并不常见。

The replyData argument contains the body of the response returned by the server, which you can then manipulate to display on your page, verify that the server-side processed the data successfully, etc. You don't have to use it (for example, if you don't return any data).

The data that you're supplying (in JSON format), will still need to be in the form of a query string, e.g. param=value. The value will also need properly encoding, using encodeURIComponent():

$.post('somescript.php', 'data='+encodeURIComponent(myJSON),
    function(replyData) {

Then, you can access the JSON in the PHP script through the $_POST superglobal:

$data = json_decode($_POST['data']);

JSON would be a little overkill for a simple input field, however. It's uncommon to use JSON in place of name/value pairs for form fields.

恬淡成诗 2024-09-22 09:48:14

1) 第三个参数是回调函数。如果您提供匿名函数(如示例中所示),则需要命名参数才能访问它。如果返回 JSON 结构,则可以访问replyData.foo 等。

2) 您可以从表单中提取值并构建 JSON 结构。

var data = {};
data.threadid = $(form).find('input[name=threadid]').val();
data.commentid = $(form).find('input[name=commentid]').val();

$.post('somescript.php', data, function(replyData) { alert(replyData.foo); } );

1) The third argument is the callback function. If you supply an anonymous function, as in your sample, you need to name the argument to access it. If you return a JSON structure, you can then access replyData.foo etc.

2) You can pull the values from your form and construct a JSON structure.

var data = {};
data.threadid = $(form).find('input[name=threadid]').val();
data.commentid = $(form).find('input[name=commentid]').val();

$.post('somescript.php', data, function(replyData) { alert(replyData.foo); } );
我的黑色迷你裙 2024-09-22 09:48:14

我从 Drupal 窃取了这个函数,并修复了导致 Zend_Json_Server 抛出异常的数组和对象上的尾随逗号。

    var toJson = function(v) {
  // typeof null == object so we check beforehand;
  if ( v == null ){
    return null;  
  }

  switch (typeof v) {
    case 'boolean':
      return v == true ? 'TRUE' : 'FALSE';
    case 'number':
      return v;
    case 'string':
      return '"'+ v +'"';
    case 'object':
      if ( !(v instanceof Array) ){
          var output = "{";
          for(i in v) {
            output = output + '"'+i+'"' + ":" + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "}"; // Fix the trailing comma error wich isn't officialy allowed.
      }else{
          var output = "[";
          for(i in v) {
            output = output + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "]"; // Fix the trailing comma error wich isn't officialy allowed.
      }
      return output;
    default:
      return null;
  }
}

现在只需向其提供数据,如下所示:

var myJsonString = toJson($('myform').serialize());

Wich 将返回从变量递归生成的 json 字符串。适用于我的大多数应用程序。

I stole this function from Drupal and fixed the trailing comma on arrays and objects wich caused Zend_Json_Server to throw exceptions.

    var toJson = function(v) {
  // typeof null == object so we check beforehand;
  if ( v == null ){
    return null;  
  }

  switch (typeof v) {
    case 'boolean':
      return v == true ? 'TRUE' : 'FALSE';
    case 'number':
      return v;
    case 'string':
      return '"'+ v +'"';
    case 'object':
      if ( !(v instanceof Array) ){
          var output = "{";
          for(i in v) {
            output = output + '"'+i+'"' + ":" + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "}"; // Fix the trailing comma error wich isn't officialy allowed.
      }else{
          var output = "[";
          for(i in v) {
            output = output + toJson(v[i]) + ",";
          }
          output = output.substr(0,output.length-1) + "]"; // Fix the trailing comma error wich isn't officialy allowed.
      }
      return output;
    default:
      return null;
  }
}

Now just feed it your data like this:

var myJsonString = toJson($('myform').serialize());

Wich will return a json string recursively generated from your variable. Works for most of my applications.

骄傲 2024-09-22 09:48:14

总的来说,我同意Andy E的观点,即如果你查看将要发布的数据的字符串,它们应该看起来像

'data='+encodeURIComponent(myJSON)

我只想清除,在实践中使用$.post 的第二个参数大多不是作为字符串:

$.post('somescript.php', 'data='+encodeURIComponent(myJSON), ... );

而是作为对象:

$.post('somescript.php', {data: myJSON}, ...);

然后 jQuery 调用 encodeURIComponent 函数并构造字符串 'data='+encodeURIComponent(myJSON)内部涉及 jQuery.param() 。更重要的是要理解,要拥有 myJSON,您必须根据包含要发布的数据的对象的某些 JSON 编码函数生成此 JSON 字符串。因此,代码在实践中看起来如下所示

$.post('somescript.php', { data: JSON.stringify(myObject) }, ...);

,其中 JSON.stringify 是来自 json2.js 的 JavaScript 函数,您可以从 http://www.json.org/js.html

In general I agree with Andy E that if you look at the string of data which will be posted they should looks like

'data='+encodeURIComponent(myJSON)

I want only to clear, that in the practice one use the second parameter of $.post mostly not as a string:

$.post('somescript.php', 'data='+encodeURIComponent(myJSON), ... );

but as a object:

$.post('somescript.php', {data: myJSON}, ...);

Then jQuery call encodeURIComponent function and construct the string 'data='+encodeURIComponent(myJSON) with respect of jQuery.param() internally. Much more important to understand, that to have myJSON you have to produce this JSON string with respect of some JSON encoding functions from an object which contains the data which you want to post. So the code will looks in the practice like following

$.post('somescript.php', { data: JSON.stringify(myObject) }, ...);

where JSON.stringify is a JavaScript function from json2.js which you can free download from http://www.json.org/js.html.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文