从PHP将字符串返回到Ajax
我有一个Ajax脚本,在用户提交时将表单信息传递给PHP。数据被插入到表中,然后向Ajax返回一个字符串。出于某种原因,我得到的不是字符串,而是页面的完整HTML代码。如何获取字符串而不是HTML代码 HTML从PHP将字符串返回到Ajax,php,ajax,Php,Ajax,我有一个Ajax脚本,在用户提交时将表单信息传递给PHP。数据被插入到表中,然后向Ajax返回一个字符串。出于某种原因,我得到的不是字符串,而是页面的完整HTML代码。如何获取字符串而不是HTML代码 HTML <form id='orderForm' action='' method='post'> <h2>Choose your pizza size</h2><hr>
<form id='orderForm' action='' method='post'>
<h2>Choose your pizza size</h2><hr>
<select name='size'>
<option value='' disabled selected>Choose a size</option>
<option value='small'>Small</option>
<option value='medium'>Medium</option>
<option value='large'>Large</option></select>
<h2>Choose your toppings</h2><hr><label><input type='checkbox' name='check_list[]' value='beef'>Beef</label>
<label><input type='checkbox' name='check_list[]' value='pepperoni'>Pepperoni</label>
<label><input type='checkbox' name='check_list[]' value='chicken'>Chicken</label>
<label><input type='checkbox' name='check_list[]' value='sausage'>Sausage</label>
<h2>Enter your details</h2><hr><input type='text' name='name' placeholder='Full Name'>
<input type='email' name='email' placeholder='Email'>
<input type='text' name='phone' placeholder='Phone number'>
<input type='text' name='address' placeholder='Address'>
<input id='zip' type='text' name='zip' placeholder='Zip Code'>
<p id='message'></p>
<input id='submitBtn' type='submit' name='submitBtn' value='Place Order'>
</form>
PHP
if (isset($_POST["email"])){
$orderId = time() + mt_rand(1,10);
$toppings = implode(', ', $_POST['check_list']);
$result = $db->prepare("INSERT INTO orders (order_id, type, pizza_type, size, toppings, name, address, email, number) VALUES (?, ?,?,?,?,?,?,?,?)");
$result->bind_param("sssssssss", $orderId, $_GET['type'], $_GET['order'], $_POST['size'], $toppings, $_POST['name'], $_POST['address'], $_POST['email'], $_POST['phone']);
$result->execute();
$db->close();
echo "?success=true&orderid=' . $orderId . '&toppings=' . $toppings";
}
在js中,我建议您使用:
ajax.done()
ajax.fail()
ajax.always()
请注意使用:
'method'
'dataType'
因此,在Js中应该是这样的:
var ajax = $.ajax({
method: 'POST',
dataType: 'json',
url: 'validation.php',
data: $("#orderForm").serialize()
});
ajax.done(function (data, textStatus, jqXHR) {
window.location = data;
});
在PHP中:
echo json_encode('your string');
编辑:
我不能发表评论,因为我是新来的,所以我会把我的新想法附加到新来的。
我刚刚又进行了一次深入测试
测试1:
我在js中分配了数据类型:'json'
和数据:$(“#testForm”).serialize()
。我提交了。在php中,我检查了接收到的值。一切都好!我使用json\u encode($uri)
回显uri字符串。我在js中收到uri字符串并应用window.location=result
。我被成功重定向
测试2
我在js中分配了数据类型:“html”
。我提交了。在php中,我检查了接收到的值。一切都好!我使用echo$uri
回送了一个uri字符串。我在js中收到uri字符串并应用window.location=result
。我被成功重定向
建议:
所以,这里一切都好。但是,用户2896120,我有点怀疑。因此:
- bind_参数的第一个参数是“sss”。但至少$orderId是整数。换成 $result->bind_参数(“dsss…”,$orderId,/…/)
- 在回显结果字符串之前关闭连接
- 在回显结果字符串之前,不要打印任何内容。无回声、打印、变量转储等
- 如果结果是收到html代码,请阅读它!是真的你的网页html代码吗?或者“早期”打印中的其他html代码(例如,在回显结果字符串之前)
<input type="text" name="order" hidden value="<?php echo $_GET['order']; ?>>
>
Obs。关于“类型”:
<input type="text" name="order" hidden value="<?php echo $_GET['order']; ?>>
不要将“type”用作“name”属性中的值。也许它被看作是一个保留的名字!客户端和数据库部分。而且,您的数据似乎正好在“type”值处插入
因此,我的意思是更改“类型”hier(为了测试,可能更改为“mytype”):
嗨,我不知道你是如何得到$\u get['type']
和$\u get['order']
if (isset($_POST["email"])){
$orderId = time() + mt_rand(1,10);
$toppings = trim(implode(',', $_POST['check_list']));
$type = $_POST['type'];
$order = $_POST['order'];
$result = $db->prepare("INSERT INTO orders (order_id, type, pizza_type, size, toppings, name, address, email, number) VALUES (?, ?,?,?,?,?,?,?,?)");
$result->bind_param("issssssss", $orderId, $type, $order, $_POST['size'], $toppings, $_POST['name'], $_POST['address'], $_POST['email'], $_POST['phone']);
try {
$result->execute();
}catch (Exception $e) {
echo $e->getMessage();
}
$db->close();
echo "?success=true&orderid=" . $orderId . "&toppings=" . $toppings;
}
表格页
<head>
<link href='index.css?<?php echo time(); ?>' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class='container'>
<div class='startContainer'>
<?php
if (!isset($_GET['type'])) {
if (!isset($_GET['success'])) {
echo "<img src='order_bg'>
<a href='?type=delivery'><div class='orderOptions'>
<i class='material-icons'>directions_car</i>
Delivery
</div></a>
<a href='?type=carryout'><div class='orderOptions'>
<i class='material-icons''>store</i>
Carry out
</div></a>
</div>";
} else {
echo "<h1>Success!</h1><p>Your order id is: " . $_GET['orderid'] . "</p><br>
<p>Toppings: " . $_GET['toppings'] . "</p>
<h1>Your pizza will be ready in:</h1>
<h2 id='counter' style='text-align: center'></h2>";
}
} else {
if (!isset($_GET['order'])) {
echo "<img src='make_pizza'>  <h2>Choose your pizza.</h1>
<a href='?type=$_GET[type]&order=custom'><div class='pizzaType'>
<img src='custom_pizza'>
<i class='material-icons'>apps</i>
Custom made
</div></a>
<a href='?type=$_GET[type]&order=grandma'><div class='pizzaType'>
<img src='grandma_pizza'>
<i class='material-icons'>local_pizza</i>
Grandma's Pizza
</div></a>";
} else {
echo "<img src='order_pizza'>
<form id='orderForm' action='' method='post'>";
if ($_GET['order'] == 'custom') {
echo "<h2>Choose your pizza size</h2><hr>
<select name='size'>
<option value='' disabled selected>Choose a size</option>
<option value='small'>Small</option>
<option value='medium'>Medium</option>
<option value='large'>Large</option></select>
<h2>Choose your toppings</h2><hr><label><input type='checkbox' name='check_list[]' value='beef'>Beef</label>
<label><input type='checkbox' name='check_list[]' value='pepperoni'>Pepperoni</label>
<label><input type='checkbox' name='check_list[]' value='chicken'>Chicken</label>
<label><input type='checkbox' name='check_list[]' value='sausage'>Sausage</label>";
}
echo "<h2>Enter your details</h2><hr><input type='text' name='name' placeholder='Full Name'>
<input type='email' name='email' placeholder='Email'>
<input type='text' name='phone' placeholder='Phone number'>
<input name='type' hidden value='" . $_GET['type'] . "' type='text'>
<input type='text' name='order' hidden value='" . $_GET['order'] . "'>";
if ($_GET['type'] == 'delivery') {
echo "<input type='text' name='address' placeholder='Address'>
<input id='zip' type='text' name='zip' placeholder='Zip Code'>
<p id='message'></p>";
}
echo "<input id='submitBtn' type='submit' name='submitBtn' value='Place Order'>
</form>";
}
}
?>
</div>
</div>
<script>
var count = 60,
timer = setInterval(function () {
$("#counter").html(count-- + " seconds");
if (count == 0) {
$("#counter").html("Order complete!");
clearInterval(timer);
}
}, 1000);
var zipCodes = ["30060", "30069", "30090", "30065", "30063", "30061", "30006", "30007", "30008", "30081", "30067", "30064", "30082", '30080', "30339", "30068", "30062", "30066", "30152", "30126", "30160", "30156", "30327", "30144", "30106", "30328", "30111", "30127", "30342"];
$("#zip").on("focus", function () {
$("#submitBtn").prop("disabled", false);
$("#submitBtn").removeAttr("style");
$("#message").text("");
})
$('#orderForm').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var zip = $("#zip").val();
if (zipCodes.indexOf(zip) == -1) {
$("#submitBtn").prop("disabled", true);
$("#submitBtn").css("background-color", "gray");
$("#message").text("We're sorry, but we do not deliver to the following zip code.");
}
else {
$.ajax({
type: 'post',
url: 'file.php', // change this to php file.
dataType: "text",
data: $("#orderForm").serialize(),
success: function (data) {
window.location = data;
}
})
}
})
</script>
</body>
为什么不使用json?@AndrewLarsen作为json\u encode($string)
?我试过了,但由于某些原因,它仍然不起作用。使用json_encode,我不会得到任何返回的内容。请尝试使用数据类型:“json”,
?更改数据类型:text
是否会有所不同?是的,它们的行为不同,当执行一个请求时,您会得到不同的响应代码>在php脚本的顶部。@AndrewLarsen在脚本顶部添加它会将我重定向到HTML代码。由于ajax是一个变量,如何执行它以使脚本运行?抱歉@user2896120,我的评论不好(我是一个非常新的:-)。我重新编辑了它,因为它不再让我保存它了。因此,我真正的注释是:jqueryAjax()——在我的答案$.ajax()调用中——执行异步HTTP请求——jQuery.ajax(url[,settings])——并返回一个jqXHR对象。在我的回答中,这个对象是“ajax”变量,进一步用于引用“success”、“error”、“complete”和其他回调。从jQuery 3.0开始,这3个回调已被弃用。“完成”、“失败”和“始终”回调将替换它们。
if (isset($_POST["email"])){
$orderId = time() + mt_rand(1,10);
$toppings = trim(implode(',', $_POST['check_list']));
$type = $_POST['type'];
$order = $_POST['order'];
$result = $db->prepare("INSERT INTO orders (order_id, type, pizza_type, size, toppings, name, address, email, number) VALUES (?, ?,?,?,?,?,?,?,?)");
$result->bind_param("issssssss", $orderId, $type, $order, $_POST['size'], $toppings, $_POST['name'], $_POST['address'], $_POST['email'], $_POST['phone']);
try {
$result->execute();
}catch (Exception $e) {
echo $e->getMessage();
}
$db->close();
echo "?success=true&orderid=" . $orderId . "&toppings=" . $toppings;
}
<head>
<link href='index.css?<?php echo time(); ?>' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class='container'>
<div class='startContainer'>
<?php
if (!isset($_GET['type'])) {
if (!isset($_GET['success'])) {
echo "<img src='order_bg'>
<a href='?type=delivery'><div class='orderOptions'>
<i class='material-icons'>directions_car</i>
Delivery
</div></a>
<a href='?type=carryout'><div class='orderOptions'>
<i class='material-icons''>store</i>
Carry out
</div></a>
</div>";
} else {
echo "<h1>Success!</h1><p>Your order id is: " . $_GET['orderid'] . "</p><br>
<p>Toppings: " . $_GET['toppings'] . "</p>
<h1>Your pizza will be ready in:</h1>
<h2 id='counter' style='text-align: center'></h2>";
}
} else {
if (!isset($_GET['order'])) {
echo "<img src='make_pizza'>  <h2>Choose your pizza.</h1>
<a href='?type=$_GET[type]&order=custom'><div class='pizzaType'>
<img src='custom_pizza'>
<i class='material-icons'>apps</i>
Custom made
</div></a>
<a href='?type=$_GET[type]&order=grandma'><div class='pizzaType'>
<img src='grandma_pizza'>
<i class='material-icons'>local_pizza</i>
Grandma's Pizza
</div></a>";
} else {
echo "<img src='order_pizza'>
<form id='orderForm' action='' method='post'>";
if ($_GET['order'] == 'custom') {
echo "<h2>Choose your pizza size</h2><hr>
<select name='size'>
<option value='' disabled selected>Choose a size</option>
<option value='small'>Small</option>
<option value='medium'>Medium</option>
<option value='large'>Large</option></select>
<h2>Choose your toppings</h2><hr><label><input type='checkbox' name='check_list[]' value='beef'>Beef</label>
<label><input type='checkbox' name='check_list[]' value='pepperoni'>Pepperoni</label>
<label><input type='checkbox' name='check_list[]' value='chicken'>Chicken</label>
<label><input type='checkbox' name='check_list[]' value='sausage'>Sausage</label>";
}
echo "<h2>Enter your details</h2><hr><input type='text' name='name' placeholder='Full Name'>
<input type='email' name='email' placeholder='Email'>
<input type='text' name='phone' placeholder='Phone number'>
<input name='type' hidden value='" . $_GET['type'] . "' type='text'>
<input type='text' name='order' hidden value='" . $_GET['order'] . "'>";
if ($_GET['type'] == 'delivery') {
echo "<input type='text' name='address' placeholder='Address'>
<input id='zip' type='text' name='zip' placeholder='Zip Code'>
<p id='message'></p>";
}
echo "<input id='submitBtn' type='submit' name='submitBtn' value='Place Order'>
</form>";
}
}
?>
</div>
</div>
<script>
var count = 60,
timer = setInterval(function () {
$("#counter").html(count-- + " seconds");
if (count == 0) {
$("#counter").html("Order complete!");
clearInterval(timer);
}
}, 1000);
var zipCodes = ["30060", "30069", "30090", "30065", "30063", "30061", "30006", "30007", "30008", "30081", "30067", "30064", "30082", '30080', "30339", "30068", "30062", "30066", "30152", "30126", "30160", "30156", "30327", "30144", "30106", "30328", "30111", "30127", "30342"];
$("#zip").on("focus", function () {
$("#submitBtn").prop("disabled", false);
$("#submitBtn").removeAttr("style");
$("#message").text("");
})
$('#orderForm').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var zip = $("#zip").val();
if (zipCodes.indexOf(zip) == -1) {
$("#submitBtn").prop("disabled", true);
$("#submitBtn").css("background-color", "gray");
$("#message").text("We're sorry, but we do not deliver to the following zip code.");
}
else {
$.ajax({
type: 'post',
url: 'file.php', // change this to php file.
dataType: "text",
data: $("#orderForm").serialize(),
success: function (data) {
window.location = data;
}
})
}
})
</script>
</body>