调用javascript函数时将javascript变量值传递给php文件
我有一个javascript函数,当点击脚本按钮时运行调用javascript函数时将javascript变量值传递给php文件,php,html,function,javascript,Php,Html,Function,Javascript,我有一个javascript函数,当点击脚本按钮时运行 //script function oyCrosswordFooter.prototype.update = function(){ var buf = ""; if (!this.puzz.started){ buf += "Game has not yet started!"; } else { buf += this.p
//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 to脚本getbuf.php
将buf发送到服务器。因此,它将在php$\u GET
数组中可用。但在将其插入数据库之前,请仔细清理它
您可能还想研究如何使用jQuery之类的JS库。它简化了很多Javascript,例如,我添加的所有代码都可以替换为:
$.get('getbuf.php', {buf: buf}, function(){
alert('buf was sent to the server');
});
不知道javascript对于这一点来说应该不是太大的问题。写一篇这样的帖子:
$.ajax({
type: 'POST',
url: '/a.php',
data: buf,
success: success,
dataType: dataType
});