gpt4 book ai didi

javascript - Ajax 请求不起作用。无法连接到服务器

转载 作者:行者123 更新时间:2023-12-03 10:20:15 26 4
gpt4 key购买 nike

我创建了一个简单的联系我们表单,它从文本字段捕获数据,然后将数据转换为 JSON 对象并使用 Ajax 发送到服务器。但我总是收到错误。成功功能不起作用。我相信它没有连接到服务器。

请告诉我哪里出错了。

HTML

body>
<h1> Contact Us </h1>
We value your feedback. Send in your questions, suggestions, ideas to help us improve our service.

<h2 align="Center"> Search us on Google Maps</h2>
<br>
<br>


<form action="contact.php" name="form" method="post">

<br>Name :<br>

<input type="text" name="fName" id="fName" required >

&nbsp; &nbsp;
<input type="text" name="lName" id="lName" required >
<br> <br>
Email: <br>

<input type="email" name="email" id="email" required >

<br> <br>
Comment: <br>

<textarea name= "comment" id = "comment" rows="8" cols="50" ></textarea>

<br> <br>

Rate our Website <select name="select" id="select" >
<option value = "1" name= "rate"> 1 </option>
<option value = "2" name= "rate"> 2 </option>
<option value = "3" name= "rate"> 3 </option>
<option value = "4" name= "rate"> 4 </option>
<option value = "5" name= "rate"> 5 </option>

</select>

<br> <br>
<input type="submit" name="submit" id="submit" value="Submit">

</form>
</body>

Javascript

<script>

$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");

var jsonArr = {
firstName :document.getElementById("fName").value,
lastName :document.getElementById("lName").value,
email :document.getElementById("email").value,
comment :document.getElementById("comment").value,
rate :document.getElementById("select").value
};


$.ajax({
url : "contact.php",
type : "POST",
data : JSON.stringify(jsonArr),
dataType : "json",
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error. not working"+ error);
console.log("Error. not working" , error);
}

});

});

});

</script>

PHP

<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>

最佳答案

首先,尝试在您的网址中添加斜杠,使其相对于您的主机:

    $.ajax({
url : "/contact.php",
type : "POST",
data : JSON.stringify(jsonArr),
dataType : "json",
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error: " + error);
console.log("Error. not working" , error);
}

});

其次,关闭 contact.php 文件中的 PHP 标签:

<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
</body>
</html>

应该是:

<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>

关于javascript - Ajax 请求不起作用。无法连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29676974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com