My requirements
- After clicking the Submit button, the data from the specified input field will be sent to the backend via AJAX.
- If the operation is successful, the information in the specified input field will be updated to the value of the `text` field in the returned JSON object.
- If the operation fails, update the text in the specified input field to "Sorry".
Implement code
$("#submit-btn").click(function() {
// 获取指定 input 元素的值
var inputVal = $("#your-input").val();
// 使用 Ajax 发送数据到后端
$.ajax({
url: "your_api_url",
type: "POST",
data: {inputVal: inputVal},
dataType: "json",
success: function(response) {
// 当请求成功时,更新指定 input 的值为返回的 JSON 数据中的 text 字段
$("#your-input").val(response.text);
},
error: function(xhr, status, error) {
// 当请求失败时,修改指定 input 的值为 "抱歉"
$("#your-input").val("抱歉");
}
});
});In the above code,#submit-btn The ID of the submit button,#your-input For specifying the data to be transmitted input Element ID. After clicking the submit button, use it. .val() Method: Specify input The element's value is then sent to the backend as data. success Use within a callback function response.text To retrieve JSON data text Field, and use .val() Set it to the specified value. input Element value. In error In the callback function, specify. input The element's value is set to "Sorry".
Of course, you need to... your_api_url Replace with your actual value, and then #your-input Replace with the data you wish to send. input elementalID.