繁体   English   中英

jQuery没有在AJAX POST请求上发送JSON

[英]jQuery not sending JSON on AJAX POST request

我在这里有点困惑,我试图使用以下代码将数据发布到我的节点js服务器:

$.ajax({type:'POST',
        url:'/map',
        data:'type=line&geometry='+str,
        success:function(msg)
        {
          console.log(msg);
        },
        datatype:'json'     
    });

这是结果:

 { type: 'line', geometry: 'b~cqCge{b[mv|q@xnyC' }

这不是JSON.I之前曾尝试使用contentType并执行以下操作:

$.ajax({type:'POST',
        url:'/map',
        data:{type:'line',geometry:str},
        success:function(msg)
        {
            console.log(msg);
        },
        datatype:'json',
        contentType:"application/json"  
    });

即使这样也没有任何改变就发送了数据。我也尝试使用第一个数据字符串的上述方法。我也尝试将processData设置为false以及代码块中的方法。

对我来说重要的是数据是JSON并使用AJAX因为我试图使用mongojs从节点js插入mongodb并且它失败

实际上dataType与输入无关,而是与输出无关。

相反,你想要的是将输入data字符串化,然后将其作为单个变量发送到后端,然后可以对其进行解码:

$.ajax({type:'POST',
    url:'/map',
    data: {data: JSON.stringify({type: 'line', geometry: str})},
    success:function(msg)
    {
       console.log(msg);
    },
    dataType:'json'     
});

在你的后端,你只需解码data ,它现在应该是JSON的一个功能完备的对象。

请注意,您需要JSON类,默认情况下JQuery不包含此功能: https//github.com/douglascrockford/JSON-js

我遇到了同样的问题,NodeJS API后端正在接收Undefined request.body。

我如何通过调用AJAX解决如下问题:

$.ajax({
    url: serviceURL,
    data: JSON.stringify(jsonData),
    dataType: 'json',
    type: 'POST',
    contentType: 'application/json',
    success: response => console.log(response),
    error: e => console.log(e)
});

请注意,我必须提到contentType: 'application/json'dataType: 'json' 另请注意,有效负载JSON数据需要JSON.stringify -ing。

使用dataType而不是datatype注意 TType Capital,

dataType:'json',

尝试这个,

$.ajax({
    type:'POST',
    url:'/map',
    data:{type:'line',geometry:str},
    dataType:'json',// use dataType not datatype
    success:function(msg) {
        console.log(msg);
    }     
});

阅读jquery.ajax()

Url = "http://example.com";

var postData = $('#selectorid').serialize();

    $.ajax({
            type: 'POST',
            data: postData+'&FormType=InsertForm',
            url: Url,
            success: function(data){
                    //console.log(data);
            },
            error: function(){
                //console.log(data);
                alert('There was an error in register form');
            }
            });

在php中发布所有值。 请试一试。

试试这个

$.ajax({ type: 'POST',
        url: '/map',
        data: {type:"line",geometry : str},
        success: function (msg) {
            console.log(msg);
        },
        dataType: 'json'
    });

像@Rohan Kumar提到的那样,用dataType替换datatype

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM