如何在原型中获得和处理ajax请求给出的json数据

How to get and process json data given by ajax request in prototype?

本文关键字:请求 ajax 数据 json 处理 原型      更新时间:2023-09-26

这是我第一次尝试制作原型。我想初始化一个AJAX请求,它应该得到一个JSON响应并发出警报。到目前为止,我已经完成了以下工作。

JS:

<script type="text/javascript">
function ajaxRequest() {
    var url = '/ajaxresponse';
    new Ajax.Request( url, {
         method: 'get',
         onSuccess: function(transport,json) {
            alert(json ? Object.inspect(json) : "no JSON object");  
         },     
         onFailure: function(){ 
            alert('Something went wrong...') 
         }  
    });
}
</script>
HTML:

<a href='javascript:ajaxRequest();'>Testing AJAX</a>
JSON来源:

function ajaxresponse() {
    // Data
    $data = array("New York", "New Yorkshire", "New Jersey");
    // encode and return json data
    echo json_encode( $data );
}

点击"测试AJAX"链接,我在警告框中得到以下结果:

no JSON object

你知道吗?

谢谢

我没有看到任何第二个变量传递到原型的onSuccess处理程序。看这里。只有运输对象。这应该有帮助:

...
onSuccess: function(transport) {
      var json = transport.responseText;
      alert(json ? Object.inspect(json) : "no JSON object");  
 }, 
...