Javascript $.ajax( type: "POST" 到php的POST方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10936407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$.ajax( type: "POST" POST method to php
提问by user1201915
I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
我正在尝试使用 jQuery 中的 POST 方法来发出数据请求。所以这是html页面中的代码:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
这是服务器上的 php 代码:
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
根本没有发出 POST 请求,我不知道为什么。这些文件位于 wamp www 文件夹中的同一文件夹中,因此至少 url 没有错误。
采纳答案by ThiefMaster
You need to use data: {title: title}
to POST it correctly.
您需要使用data: {title: title}
来正确发布它。
In the PHP code you need to echo
the value instead of return
ing it.
在 PHP 代码中,您需要使用echo
该值而不是return
ing 它。
回答by Nishu Tayal
Check whether title has any value or not. If not, then retrive the value using Id.
检查标题是否有任何价值。如果没有,则使用 Id 检索该值。
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
试试这个代码。
In php code, use echoinstead of return. Only then, javascript data will have its value.
在 php 代码中,使用echo而不是return。只有这样,javascript 数据才会有价值。
回答by manWe
Id advice you to use a bit simplier method -
我建议您使用更简单的方法-
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
试试这个,我只是觉得它的语法比 $.ajax 的语法更简单......
回答by Fnx Code
try this
尝试这个
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
在表单中按钮需要是 type="submit"
回答by Juergen
contentType: 'application/x-www-form-urlencoded'