JSON 变量在 Javascript

JSON with variables in Javascript

我正在尝试使用 JSON 发送 Rest Web 服务请求。但它抛出 Bad request(http 400) 错误。该应用程序不需要任何登录。我尝试了不同的格式,但没有任何帮助。主要问题是 JSON 变量是动态的,即用户输入的值。

var jsonObject = [];
var first_name = document.getElementById("firstName").value;
var last_name = document.getElementById("lastName").value;
var u_password = document.getElementById("password").value;
var u_password_hint = document.getElementById("passwordHint").value;
var email = document.getElementById("email").value;
var u_phone = document.getElementById("phone").value;
var u_organization = document.getElementById("organization").value;

var user = new User(first_name,last_name,email,u_password,u_password_hint,u_organization);
jsonObject.push(user);

var client = new XMLHttpRequest();
client.open("POST","https://instance.service-now.com/api/now/v1/table/user_registration_request");
client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');
client.send(body);
window.location = 'activate account.do';

function  User(first_name, last_name, email, u_password_hint, u_password, u_organization) {
    this.first_name = first_name;
    this.last_name = last_name;
    this.email = email;
    this.u_password = u_password;
    this.u_password_hint = u_password_hint;
    this.u_organization = u_organization;
}

我建议使用 ServiceNow 的 REST API explorer 测试您的 API。

未测试您的代码,但您的用户函数应该 return 一个 "user" 对象。

function User(first_name, last_name, email, u_password_hint, u_password,
  u_organization) {
  return {
    'first_name': first_name,
    'last_name': last_name,
    'email': email,
    'u_password': u_password,
    'u_password_hint': u_password_hint,
    'u_organization': u_organization,
  };
}

您可以作为 JSON 传递给

client.send(JSON.stringify(user));

不需要使用"new" var user=new User(

千辛万苦,终于找到了解决办法。原始 JSON 格式稍作修改即可使用。

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
 }
});
xhr.open("POST","https://instance.service-now.com/api/now/table/ecc_queue");

var data='{"agent":"AttachmentCreator","topic":"AttachmentCreator","name":"'+fileName+'","source":"u_itinerary_attchements:"'+sysid+'","payload":"'+encodedFile+'"}';

xhr.setRequestHeader("authorization", "Basic anBhdmFuOmpwYXZhbg==");
xhr.setRequestHeader("Content-Type", "application/json");       
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);
            };

注意:注意单引号和双引号。我搞砸了这些,花了很多时间来修复它。