【问题标题】:Is it possible to pass/compare a variable to an SQL database from within a javascript if statement?是否可以从 javascript if 语句中将变量传递/比较到 SQL 数据库?
【发布时间】:2012-04-21 01:44:48
【问题描述】:

基本上,我的代码声明了一个变量,该变量检查是否将特定字符串输入到文本框中,当用户按下回车键,然后使用子字符串时,它声明了一个变量,该变量在输入的特定单词之后包含一个字符串(如下所示) .

我想将此变量传递给 php,并最终将其与 SQL 数据库进行比较,或者(但我听说这是不安全/不可能的)直接将其与来自 javascript 的 SQL 数据库进行比较。

这可能吗?

var match = textInput.value.indexOf("string");

if (keycode == 13 && match != -1) { <- checks to see if enter is pressed + "string" has been typed.
    var some_string = text.input.value.substring(7); <- takes everything after the word "string"

这就是我想将变量“some_string”传递给 SQL 数据库的地方,以执行检查并返回 true 或 false。

我希望这很清楚,并提前感谢您的帮助。

【问题讨论】:

    标签: javascript html sql database


    【解决方案1】:

    使用 AJAX 将值传递给 PHP 请求处理程序,该处理程序在适当的数据库调用中使用该值。为安全起见,在构建 SQL 时使用mysql_real_escape_string 转义参数。然后让处理程序返回响应以指示结果(JSON/XML/text/...)。

    【讨论】:

    • 使用 jQuery 进行 ajax 调用。它把事情包装得很好。请注意链接页面末尾的示例。
    • @four33:完全一样。
    • @MarceloCantos:不,不是。您不应该使用同步 ajax,因此 if 条件中的函数调用将永远无法返回所需的值。
    • @four33:是的,看我的回答 :-)
    • @Bergi:是的,你是对的。我没有注册 OP 正在同步使用响应。
    【解决方案2】:

    您必须使用ajax request。您应该异步执行此操作,否则浏览器将挂起。

    但是异步请求与回调一起工作,并且不会返回比承诺更多的东西。所以,而不是

    function synchronous(){
        // init xhr and send
        return xhr.response; // or json-parse of response-text or something
    }
    try {
        if (synchronous() == "wanted value")
            // do something
        else
            // do something else
    } catch(e) {
        // alert a problem
    }
    

    你需要使用

    function asychronous(success, error) {
        // init xhr, register handlers and send
        // return nothing
    }
    asynchronous(function scb(data) {
        if (data == "wandted value")
            // do something
        else
            // do something else
    }, function ecb(e) {
        // alert a problem
    });
    

    【讨论】:

    • 链接了一个ajax介绍(到XmlHttpRequest)。不过,我相信你会想要使用你最喜欢的库 ajax 函数。
    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2010-12-27
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多