2017-04-12 73 views
0

我在DOM中有一個很大的數組()。

<div id="array"><?php echo serialize($bigArray); ?></div> 

我需要通過我的wordpress主題中的ajax傳遞這些數據。

$(document).on('click','#somewhere',function(){ 
     var datas = $('#array').html(); 
     $.ajax({ 
      url : ajax_object.ajaxurl, 
      type : 'post', 
      data : { 
       action:'wordpress_action', 
       array: datas 
      }, 
      success: function(res) { 
       console.log(res); 
      } 
     }); 
    }) 

在我的PHP腳本:

add_action('wp_ajax_wordpress_hook', 'my_func'); 
add_action('wp_ajax_nopriv_wordpress_hook', 'my_func'); 

function my_func(){ 
    $data = unserialize($_POST['array']); 
    print_r($data); 
    die(); 
} 

但這似乎不工作。

有什麼建議嗎? 如何通過ajax傳遞php數組? json_encode? PHP會話?

+0

我改變了我的職務。我寫錯了! – Rock

回答

0

在服務器上,您應該將您的$bigArray以JSON格式嵌入到HTML data attribute中。

PHP的JSON編碼功能被稱爲json_encode()(不是serialize(),它確實是something entirely different)。

<div id="array" data-entities="<?php htmlspecialchars(json_encode($bigArray)) ?>"> 
    ... regular HTML here ... 
</div> 

總是需要調用htmlspecialchars()當你將數據寫入HTML。


在客戶端,您可以訪問jQuery的.data()方法的數據屬性。

對於通過HTTP傳輸,您需要將數據重新編碼爲JSON。 Javascript的JSON編碼功能稱爲JSON.stringify()。請參閱:How can I use JQuery to post JSON data?

$(document).on('click', '#somewhere', function() { 
    $.ajax({ 
     url: ajax_object.ajaxurl, 
     type: 'post', 
     contentType: 'application/json', 
     data: JSON.stringify({ 
      action: 'wordpress_action', 
      array: $('#array').data('entities') 
     }) 
    }).done(function (res) { 
     console.log(res); 
    }); 
}); 
0

嘗試這樣:

echo "<script type=\"text/javascript\">\n"; 
echo "var strJson = " . json_encode($bigArray) . "\n"; 
echo "var arrAsObj = JSON.parse(strJson)\n"; 
echo "</script>\n"; 

現在你應該可以訪問頁面上這兩個變量。你應該能夠在你的ajax文章的請求主體中傳遞'arrAsObj'。如果遇到問題,請確保該腳本放在html文件中的ajax調用之前。

+0

這將返回一個javascript錯誤 – Rock

+0

最新的錯誤? – victor

0

謝謝託默勒格,你的建議我解決了我的錯誤,但我編輯你的代碼。

<div id="array" data-value="<?php echo htmlspecialchars(json_encode($bigArray)) ?>"> 

$(document).on('click','#somewhere',function(){ 
     var datas = $('#array').data('value'); 
     $.ajax({ 
      url : ajax_object.ajaxurl, 
      type : 'post', 
      data : { 
       action:'wordpress_action', 
       array: datas 
      }, 
      success: function(res) { 
       console.log(res); 
      } 
     }); 
    }) 

然後在PHP腳本:

add_action('wp_ajax_wordpress_hook', 'my_func'); 
add_action('wp_ajax_nopriv_wordpress_hook', 'my_func'); 

function my_func(){ 
    $data = $_POST['array']; 
    print_r($data); 
    die(); 
} 

這就像我預期

相關問題