如何将一些文本发布到 php 文档,然后 php 文档检查它并返回响应?
在此示例中,检查输入的值是否为“test”,然后返回并发出警报 TRUE,否则返回并发出警报 FALSE。
HTML/javascript (test_php_response.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function post_to_php() {
$.post( "test_response.php", function( data ) {
if (data == true){
alert("true");
}else{
alert("false");
}
});
}
</script>
</head>
<body>
<a href="javascript:post_to_php();" class='button'>click_here</a>
<form name="response_form" id="response_form" action="test_response.php" method="POST">
<input id="response_form_textbox" name="response_form_textbox" type="text" >
</form>
</body>
</html>
PHP (test_response.php)
<?php
$text_field = $_POST['response_form_textbox'];
if ($text_field == 'test'){
echo 'true';
}else{
echo 'false';
}
?>
<强> DEMO
----编辑以下已解决/工作版本:-----
HTML/javascript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test_response</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function post_to_php() {
$.post( "test_response.php", $('#response_form').serialize(), function(data) {
if (data === "true"){
alert("true");
}else{
alert("false");
}
});
}
</script>
</head>
<body>
<a href="javascript:post_to_php();" class='button'>click_here</a>
<form name="response_form" id="response_form" action="test_response.php" method="POST">
<input id="response_form_textbox" name="response_form_textbox" type="text" >
</form>
v.05
</body>
</html>
PHP
<?php
$text_field = $_POST['response_form_textbox'];
if ($text_field == 'test'){
echo 'true';
}else{
echo 'false';
}
?>
最佳答案
您没有发送任何数据。 $.post
的第二个参数用于该数据,但您省略了它。
因此您的 php $_POST
将为空。
发送表单数据的最简单方法是使用serialize()
$.post( "test_response.php", $('#response_form').serialize(), function( data ) {
if (data){
alert("true");
}else{
alert("false");
}
});
引用:
关于javascript - 使用 jQuery 从 PHP 发布响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729047/