我有一个 JavaScript 函数,当单击脚本按钮时运行,
//script function
oyCrosswordFooter.prototype.update = function(){
var buf = "";
if (!this.puzz.started){
buf += "Game has not yet started!";
} else {
buf += this.puzz.menu.score ; //this is the value I want to pass to a php file
if(this.puzz.menu.rank != -1){
buf += this.puzz.menu.rank;
}
}
document.getElementById("oygFooterStatus").innerHTML = buf;
}
我想将“buf”的值传递给另一个 php 文件(假设是 a.php),因为单击按钮时我需要将其存储在数据库中。谁能告诉我该怎么做吗?如果有人可以请发布完整的答案,因为我是 javascript 新手。
请注意,上述函数位于.js文件中(文件格式为.js)
最佳答案
您需要使用 Ajax,Google 上有很多有关 Ajax 的信息,但我将提供一些帮助代码:
oyCrosswordFooter.prototype.update = function(){
var buf = "";
if (!this.puzz.started){
buf += "Game has not yet started!";
} else {
buf += this.puzz.menu.score ; //this is the value I want to pass to a php file
if(this.puzz.menu.rank != -1){
buf += this.puzz.menu.rank;
}
}
var ajax;
if(XMLHttpRequest)
ajax = new XMLHttpRequest();
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");
ajax.onreadystatechange = function(){
if(ajax.readyState==4 && ajax.status==200){
alert('buf was sent to the server');
}
}
ajax.open('GET', 'getbuf.php?buf='+encodeURIComponent(buf), true);
ajax.send();
document.getElementById("oygFooterStatus").innerHTML = buf;
} enter code here
该脚本通过 GET 脚本将 buf 发送到服务器 getbuf.php
。因此它将在 php $_GET
数组中可用。不过,在将其插入数据库之前请仔细清理它。
您可能还想研究使用 JS 库,例如 jQuery。它简化了很多Javascript,例如,我添加的所有代码都可以替换为:
$.get('getbuf.php', {buf: buf}, function(){
alert('buf was sent to the server');
});
关于php - 当调用 javascript 函数时将 javascript 变量值传递给 php 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200456/