2011-09-01 58 views
2

我是JSON和AJAX的新手,因此在求助於此之前已經搜索瞭解決方案並嘗試了幾天。 我使用AJAX處理提交的PHP頁面。它保存的信息很好,但我也需要PHP頁面通過返回插入的ID。這是我到目前爲止。JSON和PHP問題

在成功:

success: function(){    
    $('#popup_name img').remove(); 
    $('#popup_name').html('Saved'); 
    $('#fade , .popup_block').delay(2000).fadeOut(function() { 
     $('#fade, a.close').remove(); //fade them both out 
     $.getJSON(pathName, function(json){ 
      alert('You are here'); 
      alert("Json ID: " + json.id); 
     }); 
    }); 
} 

然後,PHP腳本調用此方法來插入信息,並返回插入的ID:

public static function doInsertQuery($sparamQuery="",$bparamAutoIncrement=true,$sparamDb="",$sparamTable=""){ 
//do the insert 
$iReturn = 0; 
$result = DbUtil::doQuery($sparamQuery); 
if(!$result){ 
    $iReturn = 0; 
} 
elseif(!$bparamAutoIncrement){ 
    $iReturn = DbUtil::getInsertedId(); 
} 
else{ 
    $iReturn = DbUtil::getInsertedId(); 
} 

//log the insert action 
//if not a client logged in- cannot log to client db 
if(Session::get_CurrentClientId() > 0){ 
    if($sparamTable != LogLogin::table_LOGLOGINS()){ 
    $oLog = new LogDbRequest(); 
    $oLog->set_Type(LogDbRequest::enumTypeInsert); 
    $oLog->set_Request($sparamQuery); 
    $oLog->set_RowId($iReturn); 
    $oLog->set_TableName($sparamTable); 
    $oLog->set_Before("NULL"); 
    $oLog->set_After(serialize(DbUtil::getRowCurrentValue($sparamDb,$sparamTable))); 
    $oLog->insertorupdate_LogDbRequest(); 
    } 
} 
echo json_encode($iReturn); 
return $iReturn; 
} 

我希望這是有道理的。我在這裏完全失敗。任何幫助都將不勝感激! 〜Mike〜

+1

'回聲json_encode(陣列( 「ID」=> $ iReturn));' – thetaiko

+1

什麼是'$ iReturn'包含哪些內容?它是否包含'array('id'=> 123);'? – Shef

+2

我不認爲你需要成功回調中的$ .getJSON()。這會再次調用服務器。只需在您的初始結果頁面輸出ID爲json。 – ZeissS

回答

1

真的很簡單。 success函數接受與來自服務器的響應相對應的參數。

客戶端:

$.ajax({ 
    'url':'/path/to/script.php', 
    'dataType':'json', 
    'success':function(response){ //note the response argument 
     alert(response.id); //will alert the id 
    } 
}); 

服務器端:

<?php 
    //...previous stuff here... 
    $response = array('id' => $id); //where $id is the id to return to the client 
    header('Content-type: application/json'); //Set the right content-type header 
    echo json_encode($response); //Output array as JSON 
?>