简体   繁体   English

使用jQuery将JSON发送到PHP

[英]send json into php using jquery

I have a JSON from a PHP file and I want to send that output to another PHP file. 我有一个来自PHP文件的JSON,我想将该输出发送到另一个PHP文件。 This is my JavaScript: 这是我的JavaScript:

var data_1;
$.ajax({
  type:"POST",
  url:"sd.php",
  success:function(result){
        data_1 = result;
        test(data_1);
        var st = JSON.stringify(data_1);
        $.post('get.php',{q:st},function(data){
            window.location = "get.php";
        });
  }
});

And my PHP file to store the JSON: 还有我的PHP文件,用于存储JSON:

<?php 
     $obj = json_decode($_POST['q']);
     echo $obj;
 ?>

But it outputs nothing. 但是它什么也没输出。 What should I do? 我该怎么办? Please help. 请帮忙。

$.ajax({
url: 'sd.php',
type: 'POST',
data: JSON.stringify(data_1), // data_1 is a javascript object here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(returned_data) {
    alert(returned_data);
}
});

You may try this i wrote for you, but its not tested 您可以尝试我为您写的这篇文章,但未经测试

/**
 * Created by vladimirnikolic on 3/24/14.
 */
$('#submit').click(function(e){
    e.preventDefault();

            var form_data = $('#your_form').serializeArray();

            var submit_data = serializedFormToDTO(form_data);
            $.ajax({
                url: 'sd.php',
                type: 'POST',
                dataType: 'json',
                data: submit_data
            })
            .done(function(xhr) {
                $.post("get.php", {
                        q: submit_data
                    },
                    function (data) {
                        // handle data here
                        // console.log(data);
                    }, 'json');
                }
            )
            .fail(function(xhr) {
                var response_text = $.parseJSON(xhr.responseText)
                console.log(response_text);

            })
});
function serializedFormToDTO (data, json) {
    json = (typeof json !== 'undefined') ? json : false;
    if ((json !== true) && (json !== false) ) {
        console.log('invalid value of second parameter (should be true/false for json output)');
        return false;
    }

    var result = {};
    for (var i = data.length - 1; i >= 0; i--) {
        result[data[i].name] = data[i].value;
    }
    if (json === true) {
        result = JSON.stringify(result);
    }

    return result;
}

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

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