我用一個招搖腳本來生成一個休息api。Jquery ajax調用與招搖'休息API a'錯誤'
{
"swagger": "2.0",
...
},
"host": "localhost:8080",
"basePath": "/swagger-item-jaxrs",
"schemes": [ "http" ],
"consumes": [ "application/json" ],
"produces": [ "application/json" ],
"paths": {
"/item/{cd}": {
"get": {
"description": "Returns an item based on the item code passed.",
"operationId": "findItemById",
"produces": [
"application/json",
"application/xml",
"text/xml",
"text/html"
],
"parameters": [
{
"name": "cd",
"in": "path",
"description": "CD of item to fetch",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "item response",
"schema": {
"$ref": "#/definitions/item"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"item": {
"type": "object",
"required": [
"cd",
"name"
],
"properties": {
"cd": {
"type": "string"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"errorModel": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}
我可以調用api使用客戶端生成java類,我甚至可以在瀏覽器中輸入url並獲得響應。
瀏覽器:http://localhost:8080/swagger-item-jaxrs/item/0446840
響應:{"cd":"0446840","name":"ROYAL BASMATI RICE "}
招搖UI甚至可以得到相同的響應返回,並表示curl命令是:curl -X GET "http://localhost:8080/swagger-item-jaxrs/item/0446840" -H "accept: application/json"
我的Ajax代碼:
$.ajax({ url: "http://localhost:8080/swagger-item-jaxrs/item/0446840" , method: "GET" , headers: { "accept": "application/json" } }) .done(function(data) { alert('success'); console.log('success: '); console.log(data); }) .fail(function(err) { console.log('error: '); console.log(err); });
Chrome開發人員工具公司nsole結果:
error: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
任何幫助將不勝感激。
我仔細檢查了json的招搖。我在http://editor.swagger.io/#!/的Swagger Editor中使用了yaml,並下載了json,這就是它的生成過程。我添加了dataType:「text」,將localhost更改爲我的計算機名稱,將console.log更改爲err.statusText。我所得到的是'錯誤'一詞。 –
我能夠得到捲曲並運行curl命令,它可以工作。我現在唯一不能工作的是來自ajax調用,它發生錯誤,這是唯一給出的信息。 –
我終於明白了這個問題。我需要在我的JavaScript中添加一個函數來防止默認提交。 –