[英]PHP POST data array is empty
我正在使用 HTML、PHP 和 AJAX 來創建搜索字段。 這是我的 HTML 代碼:
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
這是我的 AJAX 代碼:
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert("Success");
}
});
});
在 PHP 中,我嘗試了以下操作:
$obj = $_POST['myData'];
echo $obj;
print_r($_POST);
我得到的只是:
注意:未定義索引:第 9 行 C:\\xampp\\htdocs\\workspace\\MakeMyApp\\WebContent\\search.php 中的 myData
Array ( )
我也試過:
file_get_contents('php //input')
但我也得到了空數組。 我不知道究竟是什么問題。 我錯過了什么嗎?
抱歉,我無法發表評論,因為我沒有足夠的“聲譽”。
我試圖復制你的問題,它對我來說似乎沒問題。
這是 HTML 頁面...
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
});
});
</script>
</head>
<body>
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
</body>
</html>
這是接收 PHP 頁面
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
在 ajax 請求中,您可以看到我使用警報在警報中輸出響應,但是,如果一切順利,它應該輸出接收 PHP 頁面輸出的內容。
此外,它可能沒有多大幫助,但他是我如何完成 ajax 請求; 它的代碼略少,您不必單獨定義每個表單字段(如果您有多個字段)
$(document).ready(function(){
$('#search_form').submit(function() {
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data: formData,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
return false;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.