2013-05-31 132 views
0

我是Jquery的一個大新手; 我試圖從服務器獲取一些JSON:有我的代碼:使用ajax從服務器獲取Json

$.ajax({ 
     url: "/addemail", 
     type:'POST', 
     data: $("form#form12").serialize(), 
     success: function(my_json) { 
       // I suppose that Json returned by the addmail() is in the var: my_json ? 
       //inject my_json inside some <td >  

       } 
     }); 

我的PHP函數(使用Zend IM)

public function addemailAction(){ 
$data=array(array('Email'=>'[email protected]', 
        'Name'=>'Abc Def') 
          ); 
$this->_helper->json->sendJson($data); 


    } 

我是新來的,請不要親切的投票。

+0

難道你不必在那個URL中使用一些控制器嗎?你現在可以更具體地瞭解你的代碼出了什麼問題嗎? – raina77ow

+1

不要忘記添加'dataType:'json''然後嘗試像alert(my_json.Email);''成功'內'' – Spokey

+0

@ raina77ow:試圖讓json返回的addemail(); – mboullouz

回答

2

具體的數據類型添加到Ajax調用

dataType:'json'

而在你success功能,您從my_json對象引用數組名

function(my_json) { 
    alert(my_json.Email); 
    alert(my_json.Name); 
} 

不是知識淵博的什麼

讓您的數據

$this->_helper->json->sendJson($data);

確實,我確定它只是放出json代碼,但是您可以使用json_encode輸出json以及使用對象鏈稍短一些。

echo json_encode($data);

+0

謝謝你,現在它工作正常; – mboullouz

0

這只是加入到幫助您在Zend公司,開發,因爲你已經得到了你的問題回答了一起。

如果您正在使用Zend Framework 1一個偉大的方式,看看你的服務器實際上是與JSON響應直接訪問它通過網址:

http://site/applicationName/public/controllerName/ActionNameThatReturnsJsonData/format/json 

當你訪問它,你應該看到的答覆陣列中的編碼Json格式。請記住,Zend總是要求url中存在「/ format/json」,以便知道請求是json。我想你是使用「contextSwithc或Ajaxcontext」來禁用佈局和視圖渲染。如果是這樣,那麼你需要在控制器做的是任何這些:

如果使用ContextSwitch裏:

$this->view->whateeverVariableNameYouwant = $data; 

的ContextSwitch裏_helper將您的數據自動解析到JSON。無論您傳遞給您的視圖的「變量」是什麼,它都會作爲json數據回顯。和做一樣:

echo Zend_Json::encode($data); 
相關問題