通过JavaScript将JSON数据发送到服务器

时间:2014-09-25 14:52:37

标签: javascript json post postman

我需要服务,服务的详细信息如下。

POST /API/v02/JsonWs.svc/json/V02 HTTP/1.1 [OR] POST /API/Public/v02/JsonWs.svc/json/V02 HTTP/1.1
 Host: dev.domain.us
 Content-Type: application/json; charset=utf-8
Cookie: LogicAuth=3821F201156EA833......; path=/; HttpOnly

{"Header":{"Procedure":"Family_Insert"},"Body":{"EmailAddress":"email22222@domain.net","Password":"test14","IdPhoneNumber":3051234567,"Address":{"Line1":"1234 Avenue","Line2":"Suite 900","City":"Coral","ZipCode":"33327","State":{"IdState":10}},"TimeZone":{"IdTimeZone":-5},"User":{"IdGender":1,"NameFirst":"Tom","NameMiddle":"Larry","NameLast":"Lewis","DateBirth":"10-21-1978","ClubName":"ABC","Communities":[1,2],"UserConnectTypes":[3,4]}}}

要启动的javascript代码:

var xmlhttp = new XMLHttpRequest(); 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

在你的回答中,你不必使用所有变量,我只是需要一些帮助才能让我去...

编辑: 在xmlhttp中设置请求标头后,请指定如何将json数据发送到服务器的后续步骤。我不确定将数据发送到上述服务的URL。

有人可以告诉我如何在镀铬邮递员中测试上述服务吗?

1 个答案:

答案 0 :(得分:3)

xmlhttp.send('{"Header":{"Procedure".......');

基本上,您需要构建一个JSON字符串,并调用xmlhttp.send(jsonStr)

创建JSON字符串的一种方法是这样的:

var jsonStr = JSON.stringify({
  Header: {
    Procedure: 'Family_Insert'
  },
  Body: ....
});

此外,您似乎使用了错误的地址。完整样本:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://dev.domain.us/API/v02/JsonWs.svc/json/V02');
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
var jsonStr = JSON.stringify({
   Header: {
      Procedure: 'Family_Insert'
   },
   Body: ....
});
xhr.send(jsonStr);