2016-12-13 65 views
0

我正在构建一个简化的引用系统。PHP传递带有变量的Ajax,返回不同的一个

$(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) 

如何生成的$关键变量返回索引?正如你所看到的,我试图用它替换div内容。感谢所有帮助:)

+2

'echo $ key' ..?? – David

+1

[Little Bobby](http://bobby-tables.com/)说*** [你的脚本存在SQL注入攻击风险。](http://stackoverflow.com/questions/60174/how-can- I-防止-SQL注入式-PHP)***。即使[转义字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –

+1

***请[停止使用'mysql_ *'功能](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。*** [这些扩展名](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中删除。了解[prepared](http://en.wikipedia.org/wiki/Prepared_statement )[PDO]声明(http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared- statement.php),并考虑使用PDO,[这真的很简单](http://jayblanchard.net/demystifying_php_pdo.html)。 –

回答

0

echo $key; 

只需添加到你的PHP文件的末尾。然后成功方法中的变量数据包含其值。 正如在一些评论中已经提到的那样,这段代码有一些缺点,在实际应用之前应该覆盖它。