广东话邮政JSON对象使用Jquery.post() [英] Cant Post JSON Object using Jquery.post()

查看:143
本文介绍了广东话邮政JSON对象使用Jquery.post()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有得到我的JavaScript应用程序中创建下列对象。

I have the following object that gets created in my javascript application.

    poll_data[active_question] = {
        'question': $('div.question_wrap textarea').attr('value'),
        'answers':  [
            $('div.answer_wrap input#0').attr('value'),
            $('div.answer_wrap input#1').attr('value'),
            $('div.answer_wrap input#2').attr('value'),
            $('div.answer_wrap input#3').attr('value'),
            $('div.answer_wrap input#4').attr('value'),
            $('div.answer_wrap input#5').attr('value')
        ]
    };

active_question设置为'投票',0,1,2,3,4或5取决于问题此刻正在处理。我想用下面的JS code张贴此对象的PHP脚本。

active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.

    $.ajax({
        url:            '/somewebsite/poll/create?json=show',
        type:           'POST',
        // dataType:        'json',
        data:           poll_data,
        contentType:        'application/json; charset=utf-8',
        success:        function(data) {
            alert(data);
        }
    });

我的PHP code是很简单的。

My PHP code is very simple.

    echo json_encode($_POST); exit;

当我运行该脚本,然后点击触发提交数据的按钮,我收到警报(所以实际的AJAX code ++工程),但是从我的PHP脚本的结果只是一个空数组。我认为这是一个问题的对象被构​​造的方式,但我不知道,而且一直没能找到周围的工作。

When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.

在此先感谢。

推荐答案

好了,几件事情:

poll_data不是有效的JSON对象。你将不得不使用poll_data [active_question],这是一个有效的JSON对象。 jQuery的应该正确序列化这一点。取出的contentType - 我是pretty的肯定是PHP(非阳性),但你的code会不会为我工作,直到我删除它。最后,JSON =秀追加到查询字符串没有做anything..it只会被忽略。

poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.

一对夫妇的小事情太多:您可以使用 .VAL()而不是 .attr('值'),并请你看着 .serialize()以创建您的帖子数据吗?

A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?

这篇关于广东话邮政JSON对象使用Jquery.post()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆