简体   繁体   English

通过Ajax将jQuery对象发送到PHP

[英]Send jQuery object to PHP through Ajax

I'm very aware this is a possible duplicate, but none of the other questions/answers here on Stackoverflow solve my issue, and I've seen dozens ! 很清楚 ,这是一个可能的重复,但没有任何其他问题/答案在这里#2的解决我的问题,我已经看到了几十个

Here's what I'm trying to do: Send the object in jQuery to PHP through Ajax, if possible as an array (not mandatory, but preferable). 这是我要执行的操作:如果可能,将jQuery中的对象通过Ajax发送到PHP(不是强制性的,但更可取)。

My jQuery code: 我的jQuery代码:

  var category = {
        id: $(this).data('id'),
        name: $(this).data('name'),
        brief_description: $(this).data('briefdesc'),
        description: $(this).data('desc')
    };

    $.ajax({url: '/ajax.php',
        data: {action: 'removeCategory', category_info: JSON.stringify(category)},
        type: 'post',
        success: function (result) {
            console.log(result);
        },
    error: function () {
       console.log("Error");  
    }, dataType: "json"
});

The variable category is working fine, every index has its value 变量类别工作正常,每个索引都有其值

Now my ajax.php code 现在我的ajax.php代码

$category = json_decode($_POST['category_info']);
//category['name'] should exist and have the value sent from ajax
echo "We did it?";

The problem is that the error function is called. 问题是调用了错误函数。

 json_decode($_POST['category_info'], true);

to decode it as array, otherwise it will be object 将其解码为数组,否则将成为对象

http://php.net/manual/en/function.json-decode.php http://php.net/manual/zh/function.json-decode.php

You no need to stringify. 您无需进行分类。

$.ajax({
        url: '/ajax.php',
        data: {
              action: 'removeCategory', 
              category_info:category
        },
        type: 'post',

On PHP side you will get it in $_POST['category_info']. 在PHP方面,您可以在$ _POST ['category_info']中获得它。 No any need to decode 无需解码

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

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