2015-10-24 74 views
3

我無法獲取ajax GET請求(或任何此類問題的請求)來檢索響應。我只是試圖返回在警報事件的響應:將功能添加到成功選項時,Ajax請求不起作用

<script> 
    $(document).ready(function() { 
     $('#test').click(function() { 
      $.ajax ({ 
       type: 'Get', 
       url:  'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:[email protected]))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1', 
       dataType: 'json', 
       success: function(data) { 
        alert(data); 
       } 

      }); 
     }); 
    }); 
</script> 

我能得到這個和其他類似的職位要求,採取走功能的成功選項和編輯這樣的代碼工作:

<script> 
    $(document).ready(function() { 
     $('#test').click(function() { 
      $.ajax ({ 
       type: 'Get', 
       url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:[email protected]))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1', 
       dataType: 'json', 
       success: alert('success') 

      }); 
     }); 
    }); 
</script> 

這是爲什麼?更重要的是,我如何檢索響應數據並將其傳輸到警報消息?任何幫助表示讚賞!

**更新: 在閱讀了關於這個問題的前兩個用戶的反應,這就是我:

<script> 
    $(document).ready(function() { 
     $('#test').click(function() { 
      $.ajax ({ 
       type: 'GET', 
       url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:[email protected]))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1', 
       dataType: 'json', 
       success: function(data) { 
        alert(JSON.stringify(data)); 
       }, 
       error: function(data) { 
        alert(JSON.stringify(data)); 
       } 

      }); 
     }); 
    }); 
</script> 

我能夠得到錯誤的反應,所以我可以證實,有一些有點錯誤。我還想指出,我正在從一個不同的域(而不是crm.zoho.com)發出請求,所以我應該使用jsonp?如果是這樣,我將如何更改代碼?

+0

首先糾正你的'類型:'GET'',然後專注於第一個片段,一個是正確的。但既然你有'dataType:'json'',你的成功回調方法的數據參數將有一個json對象。所以如果調用是成功的,你只會在alert中看到'Object',所以試試'alert(JSON.stringify(data))'來解決這個問題。但是,如果它失敗了,那麼添加一個'fail:function(data){}'方法並在那裏執行相同的'alert(JSON.stringify(data))'。 – TipuZaynSultan

回答

1

當你有

success: alert('success') 

你沒有一個成功的請求時,你實際上是在AJAX方法開始執行此功能。 success參數需要指向函數的指針,並且在使用alert('success')時,您正在執行的是一個函數,而不是提供指向它的指針。

,你需要嘗試的第一件事是更新類型GET而不是Get

$.ajax ({ 
    type: 'GET', 
0

嘗試使用中,.done()函數如下:

<script> 
$(document).ready(function() { 
    $('#test').click(function() { 
     $.ajax ({ 
      type: 'Get', 
      url:  'yourUrl', 
      dataType: 'json', 
      } 

     }).done(function(result) {alert(data);}) //try adding: 
      .error(function(jqXHR, textStatus, errorThrown) { 
        console.log(textStatus, errorThrown);}) 
    }); 
}); 

錯誤函數還會在控制檯中爲您提供一些關於請求狀態的信息。