JavaScript / JSON-通过JSON

时间:2018-05-08 23:14:08

标签: javascript html json url

我需要向此网址发送帖子请求。

localhost:8080/customer/add?firstName=STRING&lastName=STRING&custPhone=STRING&custEmail=STRING&notificationPreference=INTEGER

资本中的单词是可以容纳用户输入的变量。

将客户信息添加到数据的URL示例是。

localhost:8080/customer/add?firstName=Linx&lastName=Blek&custPhone=5126984758&custEmail=blek@gmail.com&notificationPreference=3

这会添加客户的名字,姓氏,电子邮件,电话号码和通知偏好。

这是我的JavaScript代码

function addCustomer() {

   var firstName = document.getElementById("firstName").value;
   var lastName = document.getElementById("lastName").value;
   var phoneNum = document.getElementById("phone").value;
   var emailAddress = document.getElementById("email").value;   
   var notifications = document.getElementById("notification").value;


   var request = new XMLHttpRequest();

   var url = "localhost:8080/customer/add?";

   request.open("POST", url, true);

   request.setRequestHeader("Content-type", "application/json");

   request.onreadystatechange = function () 
   { 
    if (request.readyState == 4 && request.status == 200) 
    {
        var json = JSON.parse(request.responseText);
        console.log(json.firstName + ", " + json.&lastName + ", " + json.&custPhone+ ", " + json.&custEmail + ", " + json.&notificationPreference);
    }
}

   var parameters = JSON.stringify({"firstName=":firstName,"&lastName=":lastName,"&custPhone=":phoneNum,"&custEmail=":emailAddress,"&notificationPreference=":notifications});




   request.send(parameters);





}​​
</script>

它从HTML字段中获取用户输入,并打开POST请求,并向URL发送请求,并将客户输入附加到URL(如下所示)。但是,目前这不起作用 - 我做错了什么?

JSON对象

  {
        "custID": 100002,
        "custEmail": "josephine_darakjy@darakjy.org",
        "custPhone": "8102929388",
        "firstName": "Josephine",
        "lastName": "Darakjy",
        "notificationPreference": 1
    },

0 个答案:

没有答案