2012-08-08 31 views
0

我有代碼工作將JSON對象從Jquery傳遞到PHP頁面。POST JSON對象從Jquery到PHP並解碼它(跨域)

問題是與發送跨域請求,如果我嘗試

dataType:'json' 
jQuery中

,它給了我一個xhttp錯誤(安全性)的錯誤,我明白了。

我也讀this post是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對象跨域? 如果這是不可能的,什麼是替代解決方案?

請告知

感謝

編輯:

jQuery代碼

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 E中的錯誤nd爲:在 爲的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 ['products']的塊,這是我的一個解析錯誤嗎?我相信這是一個明顯的錯誤,但我不能發現它。

真的對不起這個

+0

只需通過它使用jsonp得到(也許base64編碼)作爲一個get參數,然後解碼它在服務器上 – yent 2012-08-08 09:28:50

+0

哇,真的這麼簡單嗎?當然,讓我檢查.. – Mponnada 2012-08-08 09:31:13

+0

即時通訊數據作爲數據:JSON.stringify({產品:jsonProducts}),在PHP結束,我檢查if(isset($ _ POST ['products']))... ..這是正確的路嗎? – Mponnada 2012-08-08 09:48:14

回答

0

我在PHP上使用了GET參數和解碼的JSON。