2015-04-06 87 views
0

一個div我有有PHP代碼一個div(它從一個數據庫打印數據)。我做了一個AJAX功能,將數據發送到服務器而無需刷新頁面,下面的代碼:刷新AJAX的成功

var url = "loadsave.php"; 

    $('.create_save').submit(function(event) { 
     if ($('.gss_new_save').val()==""){ 
      event.preventDefault();  
     } else { 
      $.ajax({ 
        type: "POST", 
        url: url, 
        data: $('form').serialize(), 
        success: function() 
        { 

        } 
       }); 
      event.preventDefault(); 
     } 
    }); 

這是打印的代碼的另一部分。問題是,它打印的代碼只是當你刷新頁面:

<?php 
      $connect = new PDO('mysql:host=localhost;dbname=game','root',''); 
      $cmd = $connect->query('SELECT * FROM saves'); 
      $result = $cmd -> fetchAll(PDO::FETCH_ASSOC); 

      foreach ($result as $res) { 
       ?> 
       <div class="gss_save cls"> 
        <span class="gss_save_text cls"><?php echo $res['name'];?></span> 
        <span class="gss_level">lvl: <?php echo $res['level'];?></span> 
       </div> 
       <?php 
      } 
     ?> 

編輯:我補充一下:形式:

<form method="post" action="loadsave.php" class="create_save"> 
      <input type="text" class="gss_new_save" name="name"> 
      <input type="submit" style="display:none"> 
     </form> 

和loadsave.php的內容:

<?php 
     if (isset($_POST['name'])) { 
      $nombre = $_POST['name']; 
     } 

     $connect = new PDO('mysql:host=localhost;dbname=game','root',''); 

     $stm = $connect->query("SELECT * FROM saves WHERE `name` ='$nombre'"); 
     $result = $stm->fetchAll(PDO::FETCH_ASSOC); 

     if(count($result)==0){ 
      $cmd = $connect->prepare('INSERT INTO saves (name, level) VALUES (:nombre,"1")'); 
      $cmd -> bindParam(":nombre",$nombre); 
      $cmd -> execute(); 
     } 
    ?> 

它的功能就像一個魅力,但我想刷新div打印我剛剛發送的內容,我該如何實現?

+0

'...我只是sent',從發送的內容,其中,服務器或形式你發送*到*服務器? – adeneo

+0

表單就是它.. – pedritoalfonso

+0

你想把整個表單放在DIV中嗎? – adeneo

回答

2

假設腳本呼應了新的內容背:

success:function(response) { 
    $("#divID").html(response); 
} 

loadsave.php應該是:

<?php 
    if (isset($_POST['name'])) { 
     $nombre = $_POST['name']; 
    } 

    $connect = new PDO('mysql:host=localhost;dbname=game','root',''); 

    $stm = $connect->query("SELECT * FROM saves WHERE `name` ='$nombre'"); 
    $result = $stm->fetchAll(PDO::FETCH_ASSOC); 

    if(count($result)==0){ 
     $cmd = $connect->prepare('INSERT INTO saves (name, level) VALUES (:nombre,"1")'); 
     $cmd -> bindParam(":nombre",$nombre); 
     $cmd -> execute(); 
    } 

    $cmd = $connect->query('SELECT * FROM saves'); 
    $result = $cmd -> fetchAll(PDO::FETCH_ASSOC); 

    foreach ($result as $res) { 
     ?> 
     <div class="gss_save cls"> 
      <span class="gss_save_text cls"><?php echo $res['name'];?></span> 
      <span class="gss_level">lvl: <?php echo $res['level'];?></span> 
     </div> 
     <?php 
    } 

?> 
+0

我將編輯代碼於樁的另一部分試試你的答案 – pedritoalfonso

+0

dindn't工作:( – pedritoalfonso

+0

請發表您的HTML,你使用更新的代碼。 – Barmar