使用ajax创建POST请求

时间:2016-07-10 23:12:34

标签: javascript jquery ajax post request

我想在正文中使用以下数据创建一个ajax调用

{
   locations:[
      {latLng:{lat:51.524410144966154,lng:-0.12989273652335526}},
      {latLng:{lat:51.54495915136182,lng:-0.16518885449221493}},
      {latLng:{lat:51.52061842826141,lng:-0.1495479641837033}},
      {latLng:{lat:51.52850609658769,lng:-0.20170525707760403}}
   ]
}

使用fiddler编写POST工作完美,并导致以下POST请求:

POST http://www.mapquestapi.com/directions/v2/optimizedroute?key=MYKEY HTTP/2.0
User-Agent: Fiddler
Host: www.mapquestapi.com
Content-Length: 289

{
   locations:[
      {latLng:{lat:51.524410144966154,lng:-0.12989273652335526}},
      {latLng:{lat:51.54495915136182,lng:-0.16518885449221493}},
      {latLng:{lat:51.52061842826141,lng:-0.1495479641837033}},
      {latLng:{lat:51.52850609658769,lng:-0.20170525707760403}}
   ]
}

我尝试在JS中使用ajax调用发出相同的请求:

$.ajax({
        url: 'http://www.mapquestapi.com/directions/v2/optimizedroute?key=MYKEY',
        type: 'POST',
        data: JSON.stringify({locations:
        [
        {latLng:{lat:51.524410144966154,lng:-0.12989273652335526}},
        {latLng:{lat:51.54495915136182,lng:-0.16518885449221493}},
        {latLng:{lat:51.52061842826141,lng:-0.1495479641837033}},
        {latLng:{lat:51.52850609658769,lng:-0.20170525707760403}}
        ]})
    }).done(function(data){
         console.log(data);
     });

这导致了以下POST请求和错误。

POST http://www.mapquestapi.com/directions/v2/optimizedroute?key=MYKEY HTTP/1.1
Host: www.mapquestapi.com
Connection: keep-alive
Content-Length: 459
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

locations%5B0%5D%5BlatLng%5D%5Blat%5D=51.524410144966154&locations%5B0%5D%5BlatLng%5D%5Blng%5D=-0.12989273652335526&locations%5B1%5D%5BlatLng%5D%5Blat%5D=51.54495915136182&locations%5B1%5D%5BlatLng%5D%5Blng%5D=-0.16518885449221493&locations%5B2%5D%5BlatLng%5D%5Blat%5D=51.52061842826141&locations%5B2%5D%5BlatLng%5D%5Blng%5D=-0.1495479641837033&locations%5B3%5D%5BlatLng%5D%5Blat%5D=51.52850609658769&locations%5B3%5D%5BlatLng%5D%5Blng%5D=-0.20170525707760403

错误

"Error parsing JSON from Request: A JSONObject text must begin with '{' at character 0 of ,  Please see the documentation for the Directions Service at http://www.mapquestapi.com/directions/ for details on correctly formatting requests."

我确实尝试过几种不同的方式,但似乎没有任何帮助。 ajax调用有什么问题?

0 个答案:

没有答案