Javascript 如何使用jqueryajax获取POST数据
我正在尝试使用AJAX发布简单数据。我的HTML代码是Javascript 如何使用jqueryajax获取POST数据,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我正在尝试使用AJAX发布简单数据。我的HTML代码是 <input type="text" value="myvalue" id="sweet" name="sweet"> <button type="submit" id="mybtn-1"> 我的test_chat.php代码是 <?php echo $_POST["sweet"]; echo 'hello'; ?> 我想在一个名为“test_wrap”的div中回显POST数据
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
我的test_chat.php代码是
<?php
echo $_POST["sweet"];
echo 'hello';
?>
我想在一个名为“test_wrap”的div中回显POST数据。问题是点击按钮后,我只能在页面上回显“hello”
我知道这是因为load函数正在重新加载php文件,但我正在寻找一种解决方案,以便在我的页面上显示POST数据
谢谢您不需要用PHP来回显它,您可以直接从jQuery成功回调中显示它:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
您不需要使用PHP来回显它,您可以直接从jQuery成功回调中显示它:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
在post请求之后,您可以直接从
test\u chat.php
文件返回数据,这里不需要双重请求,返回如下数据:
<?php
return $_POST["sweet"].' \n hellow';
?>
希望这有帮助。在post请求之后,您可以直接从
test\u chat.php
文件返回数据,无需在此重复请求,返回如下数据:
<?php
return $_POST["sweet"].' \n hellow';
?>
希望这有帮助。在js文件中以这种方式执行ajax请求:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
在php中使用echo json_编码:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>
在js文件中以这种方式执行ajax请求:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
在php中使用echo json_编码:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>
只需再添加一件事#mybtn-1和#test_wrap都在同一个页面上,只是为了增加一点#mybtn-1和#test_wrap都在同一页上#mybtn-1和#test_wrap都在同一页上。它唯一给我的成功警报尝试在警报前添加console.log(数据)
,看看会显示什么。mybtn-1和#test_wrap都在同一页上。它唯一给我的成功警报尝试添加console.log(数据)
,然后查看警报将显示什么。