我有一个客户端表单,该表单将数据发布到服务器的URL。服务器从客户端收到POST请求时。它将响应发送回客户端。我可以在Google chrome的inspect-> network标签中看到响应。但是,我想使用警报或消息向客户端显示此响应。
客户端页面代码:
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").on('click', function(){
var a=document.forms["myForm"]["EmailAddress"].value;
if (a==null || a=="")
{
$("#EmailAddress").css("border-color", "#963634");
alert("Please Fill Email Address");
return false;
}
else
$.ajax({
url: 'http://127.0.0.1:8000/test/',
type : "POST",
data : JSON.stringify($("#myForm").serializeArray()),
success : function(result) {
alert('Data has been sent to API');
$("#myForm")[0].reset();
},
error: function() {
alert('failure');
}
})
});
});
</script>
</head>
<body>
<div id="page-wrap">
<div id="contact-area">
<center><img src="images/download.png" /></center><br/>
<form id="myForm" action="" method="post" onsubmit="return validateForm()">
<label>First Name:</label>
<input type="text" name="FirstName"/>
<label>Last Name:</label>
<input type="text" name="LastName"/>
<label for="DOB">DOB:</label>
<input type="text" name="DOB"/>
<label for="EmailAddress">Email Address:</label>
<input type="text" name="EmailAddress" id="EmailAddress"/>
<label for="Address1">Address 1:</label>
<input type="text" name="Address1"/>
<label for="Address2">Address 2:</label>
<input type="text" name="Address2" />
<label for="City">City:</label>
<input type="text" name="City" />
<label for="State">State:</label>
<input type="text" name="State"/>
<label for="PostalCode">Postal Code:</label>
<input type="text" name="PostalCode"/>
<input id="submit" type="button" name="submit" value="submit" class="submit-button">
</form>
</div>
</div>
</body>
</html>
服务器代码:
@api_view(['POST','GET',])
def TestView(request):
if request.method == 'POST':
print(request.body)
data = json.loads(request.body.decode('utf-8'))
customers_instance = Customers.objects.create(firstname=data[0]["value"],
lastname=data[1]["value"],
dob=data[2]["value"],
emailaddress=data[3]["value"],
address1=data[4]["value"],
address2=data[5]["value"],
city=data[6]["value"],
state=data[7]["value"],
postalcode=data[8]["value"])
return HttpResponse('Data has been received by API')
答案 0 :(得分:1)
您的代码看起来不错。尝试以这种方式修改它:
success: function(result) {
window.alert(result);
$("#myForm")[0].reset();
}