将JSON对象从Jquery发布到PHP并对其进行解码(跨域)


POST a JSON object from Jquery to PHP and decoding it (cross domain)

我有代码将JSON对象从Jquery传递到PHP页面。

问题在于发送跨域请求,如果我尝试

dataType:'json'

在jQuery中,它给了我一个XHTTP错误(安全性)错误,我理解。

看完这篇文章我也明白了JSONP仅适用于GET方法

这就是我创建和使用对象的方式:

function order(id, name) {
        return {
            id: id,
            name: name
        }
    }
    var orders= [];
    orders.push(order("123", "Lamb Kebab"), product("234", "Chicken"));
    var jsonOrders = $.toJSON(orders); 
    $.post(
        "process.php",
        {orders: jsonOrders },
        function(data){
            $("#result").html(data);
        }
    );

跨域传递 JSON 对象的解决方案是什么?如果这是不可能的,什么是替代解决方案?

请告知

谢谢

编辑:

J查询代码

 function product(code, type) {
        return {
            code: code,
            type: type
        }
    }
    var products = [];
    products.push(product("333", "Product one"), product("444", "Second product"));
    var jsonProducts = $.toJSON(products); 
    $.ajax({
        type: "GET",
        url: "http://page.tld/foo.php",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        data:JSON.stringify({products: jsonProducts}),
        error: function (msg) {
            //alert("error");
            console.log("Error here" +msg);         
        },

        success: function (msg) {
                console.log("Success"+msg);
        }
    });

**

PHP 端的错误是:为 foreach() 提供的参数无效 ....

**

PHP 代码(简体版)

<?php header("Content-type: application/json; charset=utf-8");
require_once('json.php');
if (isset($_GET['products'])) {
$products = json_decode($_GET["products"],"true");
foreach ($products as $product){
echo $_GET['callback'] . '(' .(json_encode($product["type"])). ')';
}
}
else
{
echo $_GET['callback'] . '(' .(json_encode("not found")). ')';
}

?>

它正在进入能够找到 $_GET['产品'] 的块,这是我的解析错误吗? 我确信这是一个明显的错误,但我无法发现它。

真的很抱歉

我使用了GET参数并在PHP端解码了JSON。