简体   繁体   English

通过Ajax调用PHP函数

[英]Call PHP Function by Ajax

I'm new for Web sites.I have a text box in my page and what i need is when onBlur that text box, call a php method that include sql query.I found something like on the web, but still does net work it.Am i doing wrong? 我是网站的新手。我的页面上有一个文本框,当onBlur该文本框时,我需要的是调用包含sql查询的php方法。我在网上找到了类似内容,但仍然可以正常工作我做错了吗?

<?php
if(isset($_POST['Greet']))
   {
      echo $_POST['Greet'];
  }
?>
<html>
<body>
<script type="text/javascript">

function sayHi()
{
     var value = $.ajax({
        type: "POST",
         url: "page.php",
        data: "Greet="+$("#Greeting").val(),
        async: false
        }).responseText;
}

</script>

<input type="text" name="Greeting" id="Greeting" onblur="sayHi()">

</body>
</html>

exit your php for usage in same script, ajax will return entire html. 退出您的php以在同一脚本中使用,ajax将返回整个html。

<?php
    if(isset($_POST['Greet']))
    {
        echo $_POST['Greet'];
        die;
    }
?>

value will have your response alert(value) value将有您的响应alert(value)

later edit: 以后编辑:

<?php
    if(isset($_POST['Greet']))
    {
        echo $_POST['Greet'];
        die;
    }
?><html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function sayHi()
{
    var value = $.ajax({
        type: "POST",
        url: "index.php",
        data: "Greet="+$("#Greeting").val(),
        async: false
    }).responseText;
    $('#result').html(value);
}

</script>
<span id="result"></span>
<input type="text" name="Greeting" id="Greeting" onblur="sayHi()">
</body>
</html>

You should include the jQuery script to your page to make $.ajax work. 您应该在页面中包含jQuery脚本,以使$ .ajax工作。

Like this: 像这样:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM