【问题标题】:Ajax call PHP Mysql public static functionAjax调用PHP Mysql公共静态函数
【发布时间】:2016-11-22 06:55:15
【问题描述】:

我和这些家伙相处得很艰难, 我怎样才能调用这种 php 类? 这是我的问题remote: 'myData.php?jquery=%jquery' 正确的调用格式是什么?

我的数据.php

public static function getproduct($p){
        $sql = "select * from products where code like '%$p%' or name like '%$p%' or id like '%$p%'";
        $query = Executor::doit($sql);
        return Model::many($query[0],new ProductData());
    }

来自 Js/Ajax 之类的:

$(document).ready(function() {

            $('input.city').typeahead({
                name: 'city',
                remote: 'myData.php?jquery=%jquery'

            });

        })

谢谢!

【问题讨论】:

  • 在 myData.php 中,包含/使用定义类的文件并调用 ClassName::getproduct($p)
  • @user3099298 我真的很蠢,我没明白。你能给我一个更简单的例子吗?干杯。
  • @Ima 贴出来的PHP/Mysql函数已经在myData.php里面了(谁还有2个函数),所以,就像我直接调用它一样,是不是错了?
  • Ypu 不能直接从 javascript 调用,您必须使用 javascript(通过 Ajax)调用 url,并且该 url 应该在 php 文件中处理。该 php 文件可以调用您想要的任何 php 函数。阅读有关 ajax 的更多信息:w3schools.com/xml/ajax_intro.asp

标签: php mysql ajax


【解决方案1】:

Product.php 文件代表你的类文件。 viewProduct.php 是您的视图文件。当您在城市输入字段中输入文本时,jQuery 将使用 GET 方法将该值传递给类文件。如果类文件从myRequest 获取值,那么它将调用静态函数并将输出发送到视图文件。

产品.php

class Product{
    public static function getproduct($p){
        // add your SQL queries
        return "This is return value ".$p;
    }
}

// call static function 
if(isset($_GET['myRequest'])) {
     echo Product::getproduct($_GET['myRequest']);
}

viewProduct.php

<input type="text" name="city" id="city"/>

<span id="result"></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#city").keyup(function(){
        var txt = $(this).val();
        $.get("product.php", {myRequest: txt}, function(result){
            $("#result").html(result);
        });
    });
});
</script>

【讨论】:

  • 现在我得到一个解析错误:语法错误,意外的“类”(T_CLASS),期待函数(T_FUNCTION)。我给你留下一个 pastebin 看看我的 myData.php 看起来如何pastebin.com/CExBQdsd
  • @fecapeluda 在单独的目录(不是您的实际项目文件夹)中创建两个文件并运行上面的代码,然后您就可以了解它是如何工作的。然后将概念应用到您的实际项目中。
猜你喜欢
  • 1970-01-01
  • 2019-10-02
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2015-07-08
  • 2013-05-13
相关资源
最近更新 更多