基本的 PHP 和 AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5298401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:54:21  来源:igfitidea点击:

Basic PHP and AJAX

phpajax

提问by Colin Martin

We have a large PHP system that I am changing to OOP and want to use AJAX to update the web pages for logged in users. I am completely self taught and good on HTML, CSS and PHP with a basic Javascript understanding.

我们有一个大型 PHP 系统,我正在将其更改为 OOP,并希望使用 AJAX 更新登录用户的网页。我完全自学,擅长 HTML、CSS 和 PHP,对 Javascript 有基本的了解。

Trying to learn AJAX with PHP is defeating me. After trying a self made set of scripts to test AJAX which wouldn't work I then went to the Internet for examples and can't get any to work. This is on my development Mac running MAMP and using my host where we keep the current system.

试图用 PHP 学习 AJAX 正在打败我。在尝试了一组自制的脚本来测试 AJAX 之后,它无法工作,然后我去 Internet 寻找示例,但无法运行。这是在我的开发 Mac 上运行 MAMP 并使用我们保留当前系统的主机。

My question is, does anybody have a simple 'hello world' set of HTML and PHP scripts that they know work which I could try to confirm that I can run something known.

我的问题是,是否有人有一个简单的“hello world”HTML 和 PHP 脚本集,他们知道可以工作,我可以尝试确认我可以运行已知的东西。

Many Thanks Colin

非常感谢科林

回答by The_Butcher

If you are going to use AJAX I would recommend using jQuery as well. This greatly simplifies the process, is tested cross-browser and has many easy to use wrapper functions.

如果您打算使用 AJAX,我也建议您使用 jQuery。这大大简化了过程,经过了跨浏览器测试,并具有许多易于使用的包装器功能。

Its really as easy as creating a PHP page called hello.php

它真的就像创建一个名为hello.php的 PHP 页面一样简单

<?php
  echo "Hello World";
?>

Then in your main page you will need to grab the jQuery library and hook it up to the document ready event.

然后在您的主页面中,您需要获取 jQuery 库并将其连接到文档就绪事件。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
     $(function(){
       $.get("hello.php", function(data){
           alert(data);
       });
    });
</script>

This in essence is the simplest AJAX hello world tutorial I know :)

这实质上是我所知道的最简单的 AJAX hello world 教程:)

回答by arnorhs

No not really, but I would recommend that you use jQuery if you're going to be doing any ajax at all. It will make your life so much easier.

不,不是真的,但如果你打算做任何 ajax,我建议你使用 jQuery。它会让你的生活变得更轻松。

Especially since all the browsers don't implement the ajax stuff the same way.

特别是因为所有浏览器都没有以相同的方式实现 ajax 的东西。

example application using jQuery+PHP for ajax calls:

使用 jQuery+PHP 进行 ajax 调用的示例应用程序:

I'm going to assume that you already have some base html document, I'm just going to include the important bits..

我将假设您已经有了一些基本的 html 文档,我将只包含重要的部分..

receiver.php:

接收器.php:

<?php
echo 'you just received me, I\'m some PHP code and ajax is definitely working...';
?>

sender.html:

发件人.html:

<p>Hello, click this button: <a id="button" href="receiver.php">Click me</a></p>
<p id="container"><!-- currently it's empty --></p>

<!-- including jQuery from the google cdn -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script type="text/javascript">
// This is our actual script
$(document).ready(function(){
    $('a#button').click(function(){
        $.ajax({
            url: this.href,
            type: 'GET',
            dataType: 'html',
            success: function (data) {
                $('#container').html(data);
            }
        });
    });
});
</script>

That should be all you need for a basic ajax application...

这应该是一个基本的 ajax 应用程序所需要的......

回答by Alan Haggai Alavi

I would suggest using jQuery'sAJAX methods, which are cross-browser and easy to use.

我建议使用jQuery 的AJAX 方法,它们是跨浏览器的且易于使用。

回答by admgvn

Here's a basic example that uses jQuery, posting values from a form to a separate PHP file validates and returns results.

这是一个使用 jQuery 的基本示例,将值从表单发布到单独的 PHP 文件以验证并返回结果。

form.php

表单.php

<html>

<head>
<title>Simple JQuery Post Form to PHP Example</title>
</head>

<body>

<!-- including jQuery from the google cdn -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">      </script>

<!-- This div will be populated with error messages -->
<div id="example_form_error"></div>

<!-- This div will be populated with success messages -->
<div id="example_form_success"></div>

<!-- Here is your form -->
<div id="example_form_enter">
    <form id="contact_modal_form" method='post' action='form_post.php'>
            <label for="Name">Enter Your Name (Not "Adam"):</label> <input class='textbox' name='Name' type='text' size='25' required />
            <button class='contact_modal_button' type='submit'>Send</button>
    </form>
</div>

<!-- This div contains a section that is hidden initially, but displayed when the form is submitted successfully -->
<div id="example_form_confirmation" style="display: none">
    <p>
        Additional static div displayed on success.
        <br>
        <br>
        <a href="form.php">Try Again</a>
    </p>
</div>

<!-- Below is the jQuery function that process form submission and receives back results -->
<script>
    $(function() {
        $("#contact_modal_form").submit(function(event) {
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                dataType: 'json',
                success: function(data) {
                    if(data.error == true) {
                        var error = $("#example_form_error");
                        error.css("color", "red");
                        error.html("Not " + data.msg + ". Please enter a different name.");
                    } else {
                        $("#example_form_enter").hide();
                        $("#example_form_error").hide();
                        $("#example_form_confirmation").show();

                        var success = $("#example_form_success");
                        success.css("color", "green");
                        success.html("Success! You submitted the name " + data.msg + ".");
                    }
                }
            });
            event.preventDefault();
        });
    });
</script>

</body>

</html>

form_post.php

表单_post.php

<?php

    // Request Post Variable
    $name = $_REQUEST['Name'];

    // Validation
    if($name == 'Adam') {
    echo json_error($_REQUEST['Name']);
    } else {
    echo json_success($_REQUEST['Name']);
    };

    // Return Success Function
    function json_success($msg) {
        $return = array();
        $return['error'] = FALSE;
        $return['msg'] = $msg;
        return json_encode($return);
    }

    // Return Error Function
    function json_error($msg) {
        $return = array();
        $return['error'] = TRUE;
        $return['msg'] = $msg;
        return json_encode($return);
    }

?>

回答by mukesh kumar

if(!$mail->Send()) {
    //echo "Mailer Error: " . $mail->ErrorInfo;
    $data[0]=array('result'=>'Mail not send');
}elseif(!$mail1->Send()){
    //echo "Mailer Error: " . $mail->ErrorInfo;
    $data[0]=array('result'=>'Mail not send');
}else {
    $data[0]=array('result'=>'Mail Send');
}