如何获取AJAX发送的JSON以与PHP一起使用 [英] How to get JSON sent by AJAX to work with PHP

查看:95
本文介绍了如何获取AJAX发送的JSON以与PHP一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要让PHP可以使用此JSON时遇到了一个又一个的障碍,所以我想知道是否有人可以在这里帮助我.

I am hitting roadblock after roadblock in my quest to get this JSON usable by PHP, so I'm wondering if someone can help me out here.

我将JSON存储在变量DivisionsJSON中:

I have JSON being stored in the variable divisionsJSON:

    var divisionsJSON = JSON.stringify(divisions);  


然后,我尝试使用.ajax发布以下内容:


Then I try to use .ajax to post with the following:

$.ajax({
     url: "divisions.php",
     type: "post",
     data: divisionsJSON,
     success: function(){
     alert("success");
       $("#result").html('submitted successfully');
     },
     error:function(){
      alert("failure");
      $("#result").html('there is error while submit');
     }   
     }); 

(我从关于SO的另一个问题复制了此内容,但是在我的html中没有id ="result"的内容-我认为我可以删除[已删除的部分]删除该部分)

(I copied this from another question on SO, but have nothing in my html with the id="result" - I think I can delete that part [deletion confirmed])

然后,我的divisions.php页面包含以下内容:

Then, my divisions.php page contains the following:

<?php 
    $url = "divisions.php";
    $json = file_get_contents($url);
    $json = utf8_encode($json);
    $elements = json_decode($json);
    var_dump($elements);
  ?>

我对PHP/ajax的经验不足,再加上对使其无法正常工作的失望,使我尝试了很多其他事情.到目前为止,我在加载divisions.php时要么为空,要么为空.我的直觉告诉我这是ajax的问题​​,但是我对PHP缺乏经验,以至于我不能自信地说我的PHP对我应该得到的东西足够正确.我已经尝试过var_dump,print_r,echo,与实际的PHP/JSON相关的divisions.php上完全没有显示任何内容.任何帮助都将不胜感激!

My inexperience with PHP/ajax combined with my frustration with getting this to work has made me try a bunch of different things. So far I've either gotten NULL or nothing when I load divisions.php. My gut tells me that it's a problem with the ajax, but I'm so inexperienced with PHP that I can't say with confidence that my PHP is correct enough to where I should be getting something back. I've tried var_dump, print_r, echo, absolutely nothing is showing up on divisions.php related to the actual PHP/JSON. Any and all help would be greatly appreciated!

使用更新的代码响应:

我在以下php中没有utf8行,并且在utf8行中添加string(0)"时得到NULL:

I am getting NULL with the following php without the utf8 line, and string(0) "" when I added in the utf8 line:

<?php
        $json = json_decode(file_get_contents('php://input'));
        $elements = utf8_encode($json);
        var_dump($elements);
?>

有什么想法吗?

针对完整的php页面进行了

Edited for full php page:

<!DOCTYPE html>

<html lang="en">

<head>  
    <meta charset="utf-8">
    <title>untitled</title>
    <link rel="stylesheet" href="styles/reset.css" />
</head>

<body>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="divisions.js"></script>
<?php
        print_r($_POST);
?>
</body>
</html>

我为php,print_r($ _ POST);、 json_decode($ _ POST);等尝试了多行,但是我根据在其他SO和此页面上看到的内容更改了很多内容我真的很发呆.

I've tried multiple lines for the php, print_r($_POST);, json_decode($_POST);, etc. but I'm changing so many things based on what I'm seeing on other SO's and this page that I'm really in a daze.

我打算创建一个数组的这段代码不会产生JSON吗?因为似乎我没有使用JSON atm.

Would this code, which I intended to make an array, not produce JSON? Because it doesn't seem like I'm working with JSON atm.

var divisions = [];
for (var i = 0; i < arr.length; i++) {
    if(arr[i].value != "N/A"){
    var obj = { "login": arr[i].login,
            "value": "http://www.value.net/index/" + arr[i].value};
    divisions.push(obj);}

推荐答案

首先,在处理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.

这篇关于如何获取AJAX发送的JSON以与PHP一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆