且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取AJAX发送的JSON以与PHP一起使用

更新时间:2023-01-02 09:36:43

首先,在处理JSON时,***的方法是尽可能不使用它.认为它是否是易碎品.您对它所做的任何事情都可能破坏它.

First of all, when dealing with JSON the best approach is to leave it alone as much as possible. Think if it as fragile goods. Anything you do to it could break it.

请记住,不要使用stringify(),实际上,您不需要,因为JQuery会检测到它并为您处理(因为他们知道它很脆弱).

With that in mind, don't use stringify() and in fact you don't need to as JQuery will detect it and handle it for you (because they know it's fragile).

第二,选项数据:需要在$ ajax()方法中提供一个对象.通常,您会这样做,

Second, the option data: in the $ajax() method needs to be given an object. Generally you would do something like this,

data: {mydata:divisionsJSON}

这样,您可以通过以下方式访问后端的JSON

That way you can access the JSON on the backend via

$json = json_decode($_POST['mydata']); 

或者,取决于您如何设置除法数组,您可以将其作为对象数据发布:正在通过$ _POST ['divisions_key'] = divisions_value;在PHP中查找并访问它;但这会导致以后出现各种问题,并且很难将前端硬链接到后端,这非常糟糕(大多数情况下,例外情况在下面).

Or, depending on how you have your divisions array set up, you could post it as the object data: is looking for and access it in PHP via $_POST['divisions_key'] = divisions_value; but that makes for all kinds of issues later and hard links the front end to the back end which is very bad (most of the time, exception is below).

此外,如果您希望得到JSON响应,则需要在原始调用中使用dataType:'JSON'选项指定该参数,以便JQuery可以适当地对其进行处理.

Also, if you are expecting a JSON response you'll need to specify that in the original call using the dataType: 'JSON' option so JQuery can handle it appropriately.

$.ajax({
 url: "divisions.php",
 type: "post",
 data: {mydata:divisions},
 success: function(response){
   $("#result").html(response.message);
 },
 error:function(response){
  $("#result").html(response.message);
 }   
 });

但是,在我们走得太远之前,JS中的除法变量令人担忧.那是从哪里来的?这是偶然的形式吗?如果是这样,您可以使用serialize()这样

But, before we get too far, that division variable in JS is troubling. Where is that sourced from? Is it a form by any chance? If so, you can use serialize() such that

var divisions = $('#myform').serialize();

这将创建key => value对,其中key是表单字段的名称,而值(显然)是该字段的值.您可以像平常一样访问PHP中的值.

This will create key=>value pairs where the key is the name of the form field and the value is (obviously) the value of the field. You can access the values in PHP just as you would normally.

在考虑前面有关数组的结构的问题时,将数据作为对象发布是可以接受的情况.如果它是一种表单,那么表单结构无论如何都将被链接到后端,因此直接在data:选项中使用该对象就可以了.这就是不理会"的第一个概念.这里的最后一种情况完全不涉及该对象.从它离开DOM到处理程序收到它的时间,它都是对象的100%.

When considering the earlier question about how your array is structured, this is an acceptable case of posting data as the object. If it's a form then the form structure is going to be linked to the backend out of necessity anyway and so the direct use of the object in the data: option is just fine. It's that whole first concept of "leave it alone". The last case here leaves that object alone completely; from the time it leaves the DOM to the time it's received by the handler it's an object 100% of the time.