【问题标题】:PHP Passing Ajax with Variable, returning with different onePHP 使用变量传递 Ajax,返回不同的变量
【发布时间】:2017-04-28 23:19:13
【问题描述】:

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

$(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 内容。感谢所有帮助:)

【问题讨论】:

标签: php ajax variables return


【解决方案1】:

只需添加一行

echo $key;

到您的 php 文件的末尾。然后success方法中的data变量包含了它的值。 正如在一些 cmets 中已经提到的,这段代码有一些弱点,您应该在实际投入使用之前加以弥补。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-31
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多