2017-07-02 91 views
0

说明:PUT/POST双引号没有逃逸到外部服务器

我想POST/PUT以下文本

{ “电子邮件”: “[email protected]”}

via xhttp.send到外部服务器。我需要来发布双引号,但我该怎么做?我阅读了关于性能,特点等等,但我仍然在一个小时或更长时间后找不到解决方案。当然,这是行不通的(因为双引号的冲突):

xhttp.send("{"email":"[email protected]"}"); 

这是剧本到现在为止:

<!DOCTYPE html> 
<html> 
<body> 

<h1>The XMLHttpRequest Object</h1> 

<button type="button" onclick="loadDoc()">Request data</button> 

<p id="demo"></p> 

<script> 
function loadDoc() { 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     document.getElementById("demo").innerHTML = this.responseText; 
    } 
    }; 
    xhttp.open("PUT", "http://www.example.com/json", true); 
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhttp.setRequestHeader('X-CSRF-Token', "csrf_token"); 
    xhttp.send("fname=Henry"); //TODO: MAKE SURE THAT EXACTLY  {"email":"[email protected]"}  WILL BE 'POSTED'. 
} 
</script> 

</body> 
</html> 

请帮助我,我不知道这一点。

+0

转义它们或使用单引号作为分隔符 –

回答

1

你可以用单引号

xhttp.send('{"email":"[email protected]"}'); 

但是字符串,最好把它从一个对象序列化到一个字符串

xhttp.send(JSON.stringify({ email :"[email protected]"})); 

你也应该发出正确的Content-Type头

xhttp.setRequestHeader("Content-Type", "application/json"); 
+0

'JSON.stringify'是要走的路。比通过转义或引用手动制作JSON要好得多。 – randomir

0

它是JavaScript,而不是HTML(当然,它嵌入在HTML中,但在脚本元素中,因此就HTML而言,您只需要担心顺序</)。

JavaScript中的转义字符是\

xhttp.send("{\"email\":\"[email protected]\"}"); 

既然你不要在数据使用单引号,你可以用它们来分隔字符串,而不是逃避内容:

xhttp.send('{"email":"[email protected]"}'); 

或者你可以使用JavaScript对象,并将其转换以JSON:

var object = {email:"[email protected]"}; 
var json = JSON.stringify(object); 
xhttp.send(json); 

除了...

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

的内容类型为JSON是application/json