如何使用POST方法将javascript / jQuery变量传递给PHP [英] How to pass javascript/jQuery variable to PHP using POST method
问题描述
这是非常基本的。我想要做的就是测量浏览器窗口的html宽度,并将该数据传递给PHP脚本,以便我可以调整传递给网站的信息。
This is really basic. All I want to do is measure the html width of a browser window, and pass that data to a PHP script so that I can adjust what information is passed to the site.
我已经将HTML宽度部分缩小了。我只是在使用AJAX将Javascript / jQuery变量传递给PHP脚本时遇到了麻烦。
I've got the HTML width part down. I'm just having trouble passing the Javascript/jQuery variable to the PHP script using AJAX.
这是Javascript / jQuery。它是用PHP编写的,以便我以后可以使用 include()
函数。
Here's the Javascript/jQuery. It is written in PHP so that I can use the include()
function later.
echo
'<script>
htmlWidth = $("html").width();
$.ajax({
type: "POST",
url: "mobileView.php",
data:{ width: htmlWidth }
})
</script>';
这是PHP:
$width = $_POST['width'];
function mobileView(){
if ($width < 950){
return true;
} else{
return false;
}
}
mobileView();
推荐答案
这是可以在文件中起作用的代码:
Here is the code that can be function within a file:
对于PHP部分,你应该将值传递给函数并调用函数。
For PHP part, you should pass value to the function and call the function.
我猜你需要从php函数返回数据到客户端。
然后,对于ajax部分,你必须捕获返回数据。
I guess you need return data to the client from the php function return. Then, for ajax part, you have to catch the return data.
<?
if(isset($_POST['width'])){
$width = $_POST['width'];
function mobileView($width){
if ($width < 950){
echo 'true';
} else{
echo 'false';
}
}
mobileView($width);
}else{
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
htmlWidth = $("html").width();
$.ajax({
type: "POST",
url: "mobileView.php",
data:{ width: htmlWidth },
success: function(data){
console.log(data);
}
})
</script>
<?
};
?>
这篇关于如何使用POST方法将javascript / jQuery变量传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!