0

I would like to call and execute a segment of PHP code located on an external file. I understand the way of doing that involves jQuery. Here's is my code so far:

<html>
<head>
    <title>test</title>
</head>

<body>

    <script src="jquery.js"></script>
    <script language="javascript" type="text/javascript"> 
         $.post("ext.php", { name: "John", time: "2pm" })
        .done(function(data) {
          alert("Data Loaded: " + data); });

        $(document).ready(function(){
    $(this).load('ext.php');});

    </script>  

</body>

And here is the external file (ext.php):

<?php
echo $_POST['name'] . ' and- ' . $_POST['time'];
?>

The code should print the variables name and time on the screen (as well as in the popup window). The popup works fine, but the code doesn't print the veriables on the screen.

Thanks :)

4

3 回答 3

4

如果您已经知道这一点,请原谅我,但如果您不知道:

您在示例中使用的是jQuery 方法$.post()的简化形式。$.ajax()我建议使用这种更简单(但更大)的格式,直到您对 AJAX 非常有信心。$.ajax()还允许您做比流线型(快速)$.post方法更多的事情。

我添加了几个输入框供您输入一些信息。另外,你需要一个地方来放置这些东西出现在屏幕上,所以我为此创建了一个 DIV。

Ajax 将数据发布到一个外部 php 文件,该文件处理它接收到的数据,并返回一个答案。它看起来像这样:

文件#1:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                $('#mybutt').click(function() {
                    var nom = $('#yername').val();
                    var tim = $('#thetime').val();

                    $.ajax({
                        type: "POST",
                        url: "receiving_file.php",
                        data: 'name=' + nom + '&time=' +tim,
                        success:function(data){
                            alert('This was sent back: ' + data);
                            $('#report').html(data);
                        }
                    }); //END ajax

                }); //END click fn

            }); //END document.ready
        </script>
    </head>
<body>

Name: <input type="text" id="yername"><br>
Time: <input type="text" id="thetime"><br><br>
<input type="button" id="mybutt" value="Go">
<br><Br>
<div id="report"></div>

文件#2:接收文件.php

<?php
    echo 'You entered: ' . $_POST['name'] . ' and- ' . $_POST['time'];
于 2013-06-04T17:44:30.683 回答
0

尝试这个:

<script type="text/javascript"> 
    $(document).ready(function(){        
        $.post("ext.php", { name: "John", time: "2pm" }).done(function(data) { 
            alert("Data Loaded: " + data);
            $('body').html(data);
        });
    });
</script>  
于 2013-06-04T17:57:21.513 回答
0

您可以像我认为的那样使用带有负载的帖子:

$(document).ready(function () {
    $(this).load('ext.php', {
        name: "john",
        time: "2pm"
    }, function (data) {
        $('body').append(data);
    });
});
于 2013-06-04T17:47:17.200 回答