通过AJAX发送JSON使用jQuery的PHPJSON、AJAX、PHP、jQuery

2023-09-10 16:22:42 作者:别爱我了不值得

我想JSON发送到使用jQuery AJAX的PHP文件,基本上就是我想要做的就是一堆子元素的值和ID的,然后将它们分配给一个JSON对象,然后通过发送对象AJAX到PHP文件,该文件随后将对其进行处理,并将其输入到数据库中。

I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.

下面是我的code,

使用Javascript / jQuery的:

Javascript/jQuery:

function test(){
    var selects = $('#systems_wrapper').find('.dropDowns');
    var newArray = new Array();

    selects.each(function(){
        var id = $(this).attr('id');
        var val = $(this).val();
        var o = { 'id': id, 'value': val };

        newArray.push(o);
    });

    $.ajax({
            type: "POST",
            url: "qwer.php",
            dataType: 'json',
            data: { json: newArray }
        });

}

PHP:

<?php
    $json = $_POST['json'];
    $person = json_decode($json);

    $file = fopen('test.txt','w+');
    fwrite($file, $person);
    fclose($file);

    echo 'success?';
?>

它创建的文件,但它是完全空白的,任何想法可能是什么?

It creates the file, but it is completely blank, any idea what it could be?

感谢名单提前!

推荐答案

您可以尝试使用 JSON.stringify()方法的数组转换成JSON自动的。只是通过输出来源于此。

You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.

data:  { json: JSON.stringify(newArray) }

希望这有助于

Hope this helps