javascript Ajax 在同一页面上发布到 php 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17007597/
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 post to php on same page not working
提问by Khanh TO
I am trying to pass a var from jQuery to PHP.
我试图将一个 var 从 jQuery 传递到 PHP。
After researching I found the most common suggestion was to do this with Post
with Ajax and store the post var using PHP.
经过研究,我发现最常见的建议是Post
使用 Ajax执行此操作并使用 PHP 存储 post var。
My PHP skills are pretty good but I can't say the same about my JavaScript skills.
我的 PHP 技能非常好,但我不能说我的 JavaScript 技能相同。
This is what I am doing but does not seem to work at all:
这就是我正在做的,但似乎根本不起作用:
// jquery libray included etc etc
<script>
$.ajax({
type: "POST",
url: "http://currentpage.com",
data: "var=value",
dataType: string
});
</script>
</head>
<body>
<?php
if($_REQUEST["var"] == "value") {
echo "var passed and stored";
}
?>
回答by Khanh TO
<script>
$.ajax({
type: "POST",
url: "index.php",
data: {var:'value'},
dataType: 'text',
success:function(data){
// Test what is returned from the server
alert(data);
}
});
</script>
回答by curious_coder
Try
尝试
<script>
$.ajax({
type: "POST",
url: "http://currentpage.com",
data: {variablename:'value'},
dataType: "text", //Available types xml, json, script, html, jsonp, text
success:function(response){
//Returned from server
alert(response);
}
});
</script>