通过jQuery提交表单发布Json

时间:2014-05-01 13:00:58

标签: javascript jquery json

HTML

<form id="join">
<div class="content">
    <h2>Join the Dodilio Exchange</h2>
    <ul>
        <li><input id="firstname" type="text" placeholder="Fast Name" name="firstname" required></li>
    </ul>
 </div>
 </form>

JS

    var register = function (firstname) {

        var obj = {
            "firstname": firstname
        }

        $.ajax({
            type: "POST",
            dataType: 'json',
            data: obj,
            url: "/rest/register/?format=json",
            success: function (data) {
                console.log('success')
                //window.location.href = '/ideas'
            }
        });
    }


    var joinForm = $('#join');
    var firstname = $('#firstname').val()

    joinForm.submit(function(e){
        console.log('submit')
        e.preventDefault();

        register(firstname)


        return false;
    })

但是它正在发布传统形式:

POST http://127.0.0.1:8000/rest/register/?format=json HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Content-Length: 233
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://127.0.0.1:8000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://127.0.0.1:8000/jointheexchange.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

firstname=&lastname=&

我对jQuery并不是非常强大,我在网络和堆栈上看了几个这样的例子,说实话,我看不出我的错误/不同。请帮助 - thx。

2 个答案:

答案 0 :(得分:1)

在我看来var firstname = $('#firstname').val()正在设置页面加载。您希望在提交处理程序中移动它,以便在提交表单时分配其值:

var joinForm = $('#join');

joinForm.submit(function(e) {
    console.log('submit');
    e.preventDefault();

    var firstname = $('#firstname').val();

    register(firstname);

    return false;
})

此外,您在上面的代码中缺少一些分号,因此我会仔细检查代码的其余部分是否存在语法错误。

答案 1 :(得分:0)

我相信你需要对你的JSON对象进行字符串化。

var dataToSend = JSON.stringify(obj);

然后,我相信,你需要更新你的ajax方法,提到内容类型是json:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: dataToSend,
            url: "/rest/register/?format=json",
            success: function (data) {
                console.log('success')
                //window.location.href = '/ideas'
            }
        });

我制作了Fiddle它似乎正在运行,如果你有小提琴手,你可以看到数据为:{“firstname”:“test”}