2017-10-15 24 views
0

我正在尋找基於點擊在PHP頁面上的鏈接改變div的內容。鏈接是通過循環創建的,我需要通過URL傳遞幾個參數。 div也是通過循環創建的,所以div的id將是可變的。我在使用AJAX時遇到了麻煩。AJAX在點擊PHP循環內更改div值

下面是我的PHP:

<?php 
if ($result3->num_rows > 0) { 

    while($row3 = $result3->fetch_assoc()) { 
     $tripDestination = $row3["tripDestination"]; 
     $sessionID = $row3["$sessionID"]; 
     $price = $row3["price"]; 

      echo "<a href=\"#\">" . $tripDestination . ' - ' . $price . "</a>"; 
      echo "<br />"; 
      echo "<div id=\"trips\"></div>"; 
    } 
} 
?> 

我需要通過在URL中兩個變量:會話ID和tripDestination。我能夠加載靜態內容,但它需要動態。這裏是我的AJAX到目前爲止

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
     $.ajax({url: "sqlUpload.php?sessionID=35&tripDestination=SFO", success: function(result){ 
      $("#div1").html(result); 
     }}); 
    }); 
}); 
</script> 

在此先感謝!

回答

0

我可能會考慮從data屬性來發送鏈路上的信息:

PHP:

<?php 
if ($result3->num_rows > 0) { 
    while($row3 = $result3->fetch_assoc()) { 
     $tripDestination = $row3["tripDestination"]; 
     $sessionID  = $row3[$sessionID]; 
     $price   = $row3["price"]; 
     // Store the organized data 
     $data   = array(
           'tripDestination'=>$tripDestination, 
           'sessionID'=>$sessionID, 
           'price'=>$price 
          ); 
     ?> 
     <!-- You can store the array into json on the data attribute --> 
     <a href="#" class="data-set" data-information='<?php echo json_encode($data) ?>'><?php echo $tripDestination.' - '.$price ?></a> 
     <br /> 
     <div class="data-response"></div> 
    <?php 
    } 
} 
?> 

的JavaScript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    // When user clicks the <a> that has the "data-set" class 
    $('.data-set').on('click',function(e){ 
     // I like to prevent default here, just incase 
     e.preventDefault(); 
     // Assign current obj 
     var getObj = $(this); 
     // Fetch the json from the attribute 
     var getData = getObj.data('information'); 
     // Send 
     $.ajax({ 
      // Just send to the page, no query string 
      url: "sqlUpload.php", 
      // I would send POST, personally 
      type: 'GET', 
      // This is the data being sent 
      data: getData, 
      success: function(response){ 
       // Presumably you want to put the response into the 
       // accompanying div, then you can just do next() 
       getObj.next('.data-response').html(response); 
     }}); 
    }); 
}); 
</script> 
+0

使用'json-encode()'服務器端不要忘記''JSON.parse()'客戶端。 [這種類似的方法](https://jsfiddle.net/4kzcx3bn/)也是可能的,注意屬性名稱。 –