因此,我是web开发新手,我需要向服务器发送POST请求。代码如下:
于飞:
<input type="text" class="form-control" placeholder="User ID" name="email" id="email">
<button class="btn btn-theme btn-block" href="#" onClick="httpPOST(email.value)" type="submit"> <iclass="fa fa-lock"></i>SIGN IN</button>
JavaScript语言:
function httpPOST(data)
{
var client = new XMLHttpRequest();
var url = "http://193.136.19.86:8080/restaurants/login/";
client.open("POST", url, true);
client.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
client.send(data);
}
如果在email.value中有一个数字,甚至是一个布尔值,代码就可以正常工作。例如,如果我在“email”输入中输入“2”,服务器会很好地接收它。但是,当我写一个真实的的email(或其他字符串)时,它会给我一个500(内部服务器错误)。
知道我做错了什么吗?
下面是使用Django开发的服务器视图:
@csrf_exempt
def logtrans(request):
#print(request)
context= RequestContext(request,{})
d=json.loads(request.body)
if request.method == 'POST':
print(d)
return HttpResponse("Done")
提前感谢!
3条答案
按热度按时间tvmytwxo1#
我自己从来没有使用过Django,但我假设您的问题是由于在浏览器中使用一种编码发送数据(URL编码的数据),而在服务器(JSON)上使用另一种编码解码。当您试图发送的数据不是有效的JSON字符串时,服务器会抛出异常(给您500内部服务器错误)。
因此,解决方案是在所有地方使用单一编码。例如,要在所有地方使用JSON,只需更改JavaScript代码中的以下两行:
cbjzeqam2#
除了你那500美元,也许它甚至可以修好它:
最好使用
$.ajax()
:aa和您的views.py
顺便说一句,我不会
csrf_exempt
,小心点。bfrts1fy3#
代码正在使用“Content-Type”、“application/x-www-form-urlencoded”,因此POST数据应采用名称的形式:值对和使用encodeURI(数据)或escacpe(数据)编码的url。
这篇文章有一般的答案Should I URL-encode POST data?,也有具体细节的链接。