PHP使用变量传递Ajax,返回不同的变量

时间:2016-12-13 19:14:31

标签: php ajax variables return

我正在构建一个简化的推荐系统。

$(document).ready( function() {

    document.getElementById("getref").onclick = function setref() {
        $.ajax({                                      
            url: 'newref.php', // the script to call to get data
            type: "POST",
            dataType: 'json',  // data format  
            data: {ip:<?php echo $_SERVER['REMOTE_ADDR'] ?>},                        
            // you can insert url arguments here to pass to api.php
            // for example "id=5&parent=6"    
            success: function(data) // on receive of reply
            {
                alert('returned ' + data); //get id
                //--------------------------------------------------------------
                // 3) Update html content
                //--------------------------------------------------------------
                $('#bottom_msg').html("<b>freegoldtrial.com/"+id+"</b>");
                // Set output element html
                // http://api.jquery.com/category/selectors/
            } 
        });
    }
});

在newref.php里面

$ip = $_POST['ip'];
$key = substr(md5(microtime()),rand(0,26),5);
include DB.php

if(! $conn ) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $conn);
$tbl_name = "refs";
$sql="INSERT INTO refs(ip, id) VALUES ('".$ip."','".$key."')";

if (!mysql_query($sql))
{
    die('Error: ' . mysql_error());
}

mysql_close($con)

如何将生成的$ key变量返回到索引?如您所见,我试图用它替换div内容。感谢所有的帮助:)

1 个答案:

答案 0 :(得分:0)

只需添加一行

即可
echo $key;

到你的php文件的末尾。然后,success方法中的 data 变量包含其值。 正如已经在一些评论中提到的那样,这段代码有一些弱点,你应该在实际投入使用之前将其覆盖。