php - 当调用 javascript 函数时将 javascript 变量值传递给 php 文件

标签 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.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/

相关文章:

php - 从 CURL JSON 响应 php 数组中获取特定值

javascript - 如果 div 为空,如何修复 onclick 不触发?

c - 编写使用指针复制字符串的函数时出错

php - 如何通过变量调用函数

php - 如何创建 nouser/nogroup 以便 WordPress 可以写入文件?

javascript - 如何解决未捕获的类型错误: Illegal invocation jquery ajax

php - 如何使用 PHP 或 HTML 但不使用 JS 创建简单的树形菜单?

javascript - 禁用浏览器缓存

javascript - 如何使用 jQuery 遍历嵌套的 HTML div 元素

azure - 尝试了解 Azure Durable Function 上下文