[英]How to GET data from API
My API URL contains a payment transaction ID.我的 API URL 包含付款交易 ID。 I want to GET the data about this transaction from my API.
我想从我的 API 获取有关此交易的数据。 The part that says
console.log(response);
说
console.log(response);
is where I need to GET the data from the API.是我需要从 API 获取数据的地方。 I will then fill this data into labels.
然后我会将这些数据填充到标签中。 How can I do this?
我怎样才能做到这一点? I am using jQuery, ASP.NET, and C#.
我正在使用 jQuery、ASP.NET 和 C#。 Thanks.
谢谢。
$.ajax(settings).done(function(response) {
console.log(response);
});
Adding 'success' and 'error' methods to the ajax call will help fetch the data and error codes.向 ajax 调用添加“成功”和“错误”方法将有助于获取数据和错误代码。
Here is a working example:这是一个工作示例:
$.ajax({
type: "GET",
contentType: "application/json",
url: "URL_WITH_TRANSACTION_ID",
headers: {
"Authorization": "auth-header-string"
},
success: function (output) {
console.log("Success: " + JSON.stringify(output))
},
error: function (e) {
console.log("ERROR : ", e.responseText)
}
})
Maybe native fetch is better choice?也许本机获取是更好的选择? Just suggestion.
只是建议。
const { transaction_id } = await fetch(settings).then(r => r.json())
Tell the $.ajax
function to expect a JSON
response.告诉
$.ajax
函数期待JSON
响应。 Do this by adding "datatype": "json"
to the settings object.通过将
"datatype": "json"
到设置对象来做到这一点。 This now means that the response you receive will be treated as JSON
, meaning if it is a string with an object in it, it will turn the string into a workable object for you.这现在意味着您收到的响应将被视为
JSON
,这意味着如果它是一个包含对象的字符串,它会将字符串转换为您可以使用的对象。
From the jQuery documentation:来自jQuery 文档:
dataType: The type of data that you're expecting back from the server.
dataType:您期望从服务器返回的数据类型。 If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 脚本中将执行脚本,其他任何类型都将以字符串形式返回)。
function SubmitTransaction() {
// Card Card US Transaction Settings and Data
var settings = {
"url": "URL_WITH_TRANSACTION_ID",
"method": "GET",
"dataType": "json", // Add this line.
"headers": {
"X-Forte-Auth-Organization-Id": "ORGID",
"Authorization": "AUTHID",
"Content-Type": "application/json",
},
}
$.ajax(settings).done(function(response) {
console.log(response.transaction_id);
console.log(response.organization_id);
console.log(response.location_id);
console.log(response.status);
// etc..
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.