jQuery Ajax发布不起作用

时间:2013-04-26 17:18:23

标签: php javascript jquery ajax

我的jQuery ajax帖子无效。这是javascript

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' 

4 个答案:

答案 0 :(得分:0)

这样的事情:

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

比PHP:

echo $_POST["data"];

比解析它什么......

答案 1 :(得分: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'    
    });
}
}

答案 2 :(得分: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'    
    });
  }
}

然后,$_POST['postData']print_r var_dump上应该有一个$_POST变量。

答案 3 :(得分:0)

我删除后的工作

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