1

初めてAJAXを使用してDBにレコードを挿入しようとしています。私は次のものを持っています...

 <form>
     <input type="text" id="salary" name="salary">
     <input type="button" onclick="insertSalary()">
 </form>

AJAX

<script type="text/javascript">

function insertSalary()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('current-salary').innerHTML=xmlhttp.responseText;
    }
  };
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}

</script>

PHP

$uid = $_SESSION['oauth_id'];      
$monthly_income = mysql_real_escape_string($_POST['salary']);

#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;

Nowmyデータは、「0」として入力されている「給与」以外のテーブルに挿入されています。

挿入すると、div 'current-salary' もあり、そこに入力された値のみを入力する必要があります。どこが間違っているのか理解するのを手伝ってくれますか?

4

1 に答える 1

4

時間、労力、心の痛みを大幅に節約したい場合は、ajaxリクエストにjqueryライブラリを使用してください。http://jquery.com/からダウンロードできます。

参照(スクリプトタグ)をjqueryスクリプトに追加すると、ajaxリクエストのJavaScriptは次のようになります。

function insertSalary()
{
    var salary = $("#salary").val();
    $.post('insert_salary.php', {salary: salary}, function(data) 
    {
        $("#current-salary").html(data); 
    });
}

また、URLとして「insert_salary.php」を使用することは、それが相対パスであり、現在実行中のスクリプトのフォルダーにある必要があることを意味することにも注意してください。

phpスクリプトは、current-salaryタグにも挿入したいものをエコーする必要があります。

于 2012-04-12T19:21:37.600 に答える