html 无法在HTTP POST中发送字符串

xqnpmsa8  于 2022-12-02  发布在  其他
关注(0)|答案(3)|浏览(177)

因此,我是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")

提前感谢!

tvmytwxo

tvmytwxo1#

我自己从来没有使用过Django,但我假设您的问题是由于在浏览器中使用一种编码发送数据(URL编码的数据),而在服务器(JSON)上使用另一种编码解码。当您试图发送的数据不是有效的JSON字符串时,服务器会抛出异常(给您500内部服务器错误)。
因此,解决方案是在所有地方使用单一编码。例如,要在所有地方使用JSON,只需更改JavaScript代码中的以下两行:

client.setRequestHeader("Content-Type", "application/json");
client.send(JSON.stringify(data));
cbjzeqam

cbjzeqam2#

除了你那500美元,也许它甚至可以修好它:
最好使用$.ajax()

function httpPOST(data){       
   $ajax({
       url: "/restaurants/login/"; // always relative path!
       type: "post", 
       data: {data: data} 
   }).done(function(response){
       if(data.ok == 'ok'){
         alert(data.response);
       }
   });       
}

aa和您的views.py

from django.core.serializers import json

@csrf_exempt
def logtrans(request):
   data = {}
   if request.method == 'POST':
       print request.POST.get('data')
       data['ok'] = 'ok'
       data['response']= 'Done'
       return HttpResponse(json.dumps(data), content_type="application/json")
   data['ok'] = 'bad'
   data['response']= 'not post request'
   return HttpResponse(json.dumps(data), content_type="application/json")

顺便说一句,我不会csrf_exempt,小心点。

bfrts1fy

bfrts1fy3#

代码正在使用“Content-Type”、“application/x-www-form-urlencoded”,因此POST数据应采用名称的形式:值对和使用encodeURI(数据)或escacpe(数据)编码的url。
这篇文章有一般的答案Should I URL-encode POST data?,也有具体细节的链接。

相关问题