在同一页面上将Ajax转换为PHP [英] Ajax to PHP on the same page

查看:88
本文介绍了在同一页面上将Ajax转换为PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量发送到进行AJAX调用的同一页面.

I’m trying to send variables to the same page that makes the AJAX call.

仅当我分离PHP脚本时(例如process.php并相应地更改AJAX url),我才能获得成功的结果.

I receive successful result only if I separate the PHP script (e.g. process.php and change the AJAX url accordingly).

index.php

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(function() { 
        $('form').submit(function(e) { 
            e.preventDefault();
            $.ajax({
                type        : 'POST',
                url         : 'index.php',
                data        : $(this).serialize(),
                dataType    : 'json',
                encode      : true
            })
            .done(function(data) {
                $('#result').html(data);    
            })
        });
    }); 
</script>
</head>

<body>
<?php
    $data = array();
    if(isset($_POST['name'])) {
        $data = 'You entered: ' . $_POST['name'];       
        echo json_encode($data);        
    }
?>
    <form>
        <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>

    <div id="result"></div>
</body>

同一页是否可以捕获和处理我们使用AJAX传递的变量?

Is it possible for the same page to capture and process variables we pass using AJAX?

推荐答案

您在AJAX设置中设置了dataType : json,因此您应该echo一个

You set dataType : json in AJAX settings, so that you should echo a json object instead of a String (HTML).
Use exit() instead of echo, and put your PHP at the very top of the page. So that no HTML is echoed before you check if $_POST['name'] exists.

另一件事是,您的$data = array()会在该行上转换为字符串:

Another thing is that your $data = array() is converted to string on that line:

$data = 'You entered:' . $_POST['name'];

应为$data[] = ...

<?php
    $data = array();
    if(isset($_POST['name'])) {
        $data[] = 'You entered:' . $_POST['name'];
        exit(json_encode($data));       
    }
?>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(function() { 
        $('form').submit(function(e) { 
            e.preventDefault();
            $.ajax({
                type        : 'POST',
                url         : 'index.php',
                data        : $(this).serialize(),
                dataType    : 'json',
                encode      : true
            })
            .done(function(data) {
                $('#result').html(data);    
            })
        });
    }); 
</script>
</head>

<body>
    <form>
        <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>
    <div id="result"></div>
</body>

这篇关于在同一页面上将Ajax转换为PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆