Ajax响应状态为200,但显示错误消息

Ajax response status 200 but shows error message

本文关键字:显示 错误 消息 响应 状态 Ajax      更新时间:2023-09-26

我得到的状态为200,但它正在打印错误消息alert("error...");内的消息。为什么如此?

function makeSelect() {
    var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
    var url = "http://dukano.co/sakhidev/retailon/productoption/values";
    alert(url);
    var jsondata = $j('#customoption').serialize();     
    alert("jsondata: " + JSON.stringify(jsondata));
    $j.ajax({    
        type : 'POST',
        url : url,
        data : jsondata,
        dataType : 'json',
        success : function(response) {
            console.log("calling");
            console.log(response);
            alert("call success");
            alert("response data:" + JSON.stringify(response));  
            if (response.status == 200) {
                console.log("yes");
            } else if (response.status == "error") {
                console.log("no");
            }
        },
        error : function(response) {
            alert("error...");
            alert("response:" + JSON.stringify(response));
            console.log(response);
        }
    });
}

Magento的控制器函数返回json值

  public function valuesAction(){
            $blouseoption = $this->getRequest()->getParam('blouseoption');
            $sareefinishing = $this->getRequest()->getParam('sareefinishing');
            $data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
            Mage::dispatchEvent('product_custom_option', $data);
            $jsonData = json_encode(array($blouseoption, $sareefinishing));
            $this->getResponse()->clearHeaders()
             ->setHeader('Content-type','application/json',true);
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
            $this->getResponse()->sendResponse();
    }

当你使用

 dataType: "json"

将响应计算为JSON并返回一个JavaScript对象。任何格式错误的JSON都将被拒绝,并抛出解析错误。

这意味着如果服务器返回带有200 OK status的无效JSON,则jQuery触发错误函数并将textStatus参数设置为"parsererror"

确保服务器返回有效的JSON。空响应也被认为是无效的JSON;例如,你可以返回{}或null来验证JSON。尝试检查错误中的textStatus。

 error : function(jqXHR,textStatus,errorThrown)
   {console.log(textStatus)}

如果打印"parsererror",那么你返回的json肯定有问题。请核对一下。

更多信息

选择答案

您可以返回状态204而不返回任何响应,而不是返回状态200并返回空响应。状态204为No Content。在这种情况下,JQuery不应该抛出任何错误。