2016-04-01 8 views
1

私はajax関数に値を渡そうとしています。これはフォーム上でシンプルで、期待通りに動作していました(下の例ではidをgal_id1に変更しました)が、アンカーの値渡しに未定義のエラーが発生しています。アンカーでajaxに値を渡します。

<html> 
<head> 
<script> 
function ajax_post(){ 
    // Create our XMLHttpRequest object 
    var hr = new XMLHttpRequest(); 
    // Create some variables we need to send to our PHP file 
    var url = "ajax_json_gallerySQL.php"; 
    var gid = document.getElementById("gal_id").value; 
    var vars = "gal_id="+gid; 
    hr.open("POST", url, true); 
    // Set content type header information for sending url encoded variables in the request 
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    // Access the onreadystatechange event for the XMLHttpRequest object 
    hr.onreadystatechange = function() { 
     if(hr.readyState == 4 && hr.status == 200) { 
      var return_data = hr.responseText; 
      document.getElementById("status").innerHTML = return_data; 
     } 
    } 
    // Send the data to PHP now... and wait for response to update the status div 
    hr.send(vars); // Actually execute the request 
    document.getElementById("status").innerHTML = "processing..."; 
} 
</script> 
</head> 

<body> 
<h2>Test Pictures. </h2> 

THis is working 
<input id="gal_id1" name="gal_id1" type="text"> <br><br> 
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();" > <br><br> 
<div id="status"></div> 
<?php 

$myValue='13'; 
This is not working 
echo "<td> <a id='gal_id' name='gal_id' href='#' onClick='ajax_post();' value='13' ><img src='images/Parents/Brook/Brook1.jpg' alt='Image' width='270' height='203'></a><br><br>"; 

?>   


</body> 
</html> 

答えて

1

アンカーは、入力が行うのと同じ方法で値を持っていないので、.valueは動作しません。その代わりにできることは、使用することですdocument.getElementById("gal_id").getAttribute('value')

これは言いましたが、おそらくデータ属性を使用しているはずです。

<a data-value="13" id="gal_id">

、次いで

document.getElementById("gal_id").dataset.value

More information on data attributes

+0

すごくうまくいった! – user1956040

関連する問題