2013-04-26 103 views
0

我的jQuery ajax發佈不起作用。這裏是我保存數據的JavaScriptjQuery Ajax發佈不起作用

function SocialButtons() { 
var $buttonWrapper = jQuery('.WrapperDiv'); 
if ($buttonWrapper.length){ 
    var postData = $buttonWrapper.html(); 
    jQuery.ajax({ 
     type: 'POST', 
     url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php', 
     data: postData, 
     cache: false, 
     success: function(data) { 
      console.log(data); 
     }, 
     contentType: "application/json", 
     dataType: 'json'  
    }); 
} 
} 

被張貼一個隱藏的DIV中像

<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div> 

所有我正在從post.php中頁面返回是一個空數組。這裏是我的代碼post.php

<?php 
if(isset($_POST)){ 
    print_r($_POST); 
} else { 
    echo "0"; 
} 
?> 

任何想法什麼是錯的?

編輯:它的工作之後,我刪除

contentType: "application/json", 
    dataType: 'json' 
+0

的HTML抓住也只是一個字符串後的工作?你需要從中創建一個真正的數組。 – PlantTheIdea 2013-04-26 17:20:49

+1

postData只是一個字符串,而不是一個對象。使用字符串時,字符串必須作爲查詢字符串構建,而不是JSON。 – adeneo 2013-04-26 17:21:04

+0

@adeneo:任何小提琴? – 2013-04-26 17:42:02

回答

0

它我刪除

contentType: "application/json", 
dataType: 'json' 
0

什麼是這樣的:

var postData = "data=" + encodeURCIComponent($buttonWrapper.html()); 

比PHP:

echo $_POST["data"]; 

比解析它或什麼的。 ...

0

幾件事情要嘗試,

嘗試先將數據直接傳遞給數據對象。如果 工作,那麼你可以調試,看看爲什麼它沒有準備好你的隱藏div。

而不是$ buttonWrapper.html嘗試$ buttonWrapper.text();

function SocialButtons() { 
var $buttonWrapper = jQuery('.WrapperDiv'); 
if ($buttonWrapper.length){ 
    var postData = $buttonWrapper.**text**(); 
    jQuery.ajax({ 
     type: 'POST', 
     url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php', 
     data: **{'id':1}**, 
     cache: false, 
     success: function(data) { 
      console.log(data); 
     }, 
     contentType: "application/json", 
     dataType: 'json'  
    }); 
} 
} 
0

內,您的jQuery的Ajax調用,您的數據沒有被設置爲$ _ POST變量名。因此,爲什麼沒有被顯示

試着改變你的功能,這一點:

function SocialButtons() { 
    var buttonWrapper = jQuery('.WrapperDiv'); 
    if (buttonWrapper.length){ 
    var postData = buttonWrapper.html(); 
    jQuery.ajax({ 
    type: 'POST', 
    url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php', 
    data: {postData: postData}, 
    cache: false, 
    success: function(data) { 
     console.log(data); 
    }, 
    contentType: "application/json", 
    dataType: 'json'  
    }); 
    } 
} 

那麼你應該在你的print_r$_POSTvar_dump一個$_POST['postData']變量。

+0

對不起,它不工作。 – 2013-04-26 17:41:38

+0

@rahulRam看我的編輯。取出buttonWrapper前面的'$',看看是否有效。 – 2013-04-26 17:45:33