Nil*_*lim 2 javascript php variables parse-platform server
我有一个文件lightstatuspage.php,在其中,我有HTML,JavaScript和PHP代码.我在代码的JavaScript部分中使用了一些变量,我试图将这些变量传递给服务器,方法是将它们传递给代码的PHP部分.但是,这不起作用.
我正在使用$.post("lightstatuspage.php", slider_val);,然后在PHP部分,我通过做调用变量$_GET['rangeslider_val'];.
我做错了什么,我能做些什么来从JavaScript获取变量并将其发送到服务器?
function show_value(x)
{
document.getElementById("slider_value").innerHTML=x;
event.preventDefault();
var slider_val = x;
var query = new Parse.Query(Post);
query.first({
success: function(objects){
objects.set("slider_val", slider_val);
objects.setACL(new Parse.ACL(Parse.User.current()));
return objects.save();
window.location.href = "lightstatuspage.php?rangeslider_val=" + slider_val;
}
})
}
Run Code Online (Sandbox Code Playgroud)
PHP代码是:
<?php
$_GET['rangeslider_val'];
print($rangeslider_val);
?>
Run Code Online (Sandbox Code Playgroud)
首先添加Jquery
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
Run Code Online (Sandbox Code Playgroud)
在关闭body标签之前到页面的末尾.将Javascript变量发送到PHP.最好的方法是使用Ajax.并将以下代码添加到您的JavaScript. 不要忘记以下代码应该是一个事件.例如,点击按钮或类似的东西
$( document ).ready(function() {
var x = $('#input1').val();
//or var x= 15;
$.post("lightstatuspage.php",
{
'rangeslider_val': x
},
function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
// you can show alert or not
});
});
Run Code Online (Sandbox Code Playgroud)
在PHP中,您可以使用:
$value = $_POST['field1'];
Run Code Online (Sandbox Code Playgroud)
现在你的变量在php的$ value中.
PS:后端页面和HTML页面应该在同一个域上,或者您必须检查跨源资源共享
用户接受此解决方案的第二个解决方案是代码:
$.get("lightstatuspage.php?rangeslider_val=" + slider_val,function(res) {
console.log(res);
});
Run Code Online (Sandbox Code Playgroud)
第二种方式只是POST和GET方法的区别
第三种解决方案 如果你不想在你的项目中使用Jquery,你需要纯粹的javascript,你可以使用下面的代码
var str = "Send me to PHP";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "lightstatuspage.php?rangeslider_val=" + str, true);
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)