2017-10-15 10 views
0

PHPページでクリックされたリンクに基づいてdivの内容を変更したいと考えています。リンクはループを介して作成され、URLを介していくつかのパラメータを渡す必要があります。 divもループを通して作成されるので、divのidは可変になります。これを実現させるためにAJAXに問題があります。セッションIDとtripDestination:私はURLに2つの変数を渡す必要がAJAXはPHPループ内のクリックでdiv値を変更します

<?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>"; 
    } 
} 
?> 

以下は私のPHPです。私は静的コンテンツを読み込むことができましたが、動的である必要があります。これまでの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/)も可能です。プロパティ名には注意が必要です。 –

関連する問題