[英]How to call a RESTful web service's function from an html page by javascript
我有一個RESTful Web服務(java),我想通過“提交”按鈕將獲取請求發送到Web服務。
Web服務中稱為“ test”的函數將從html頁面中輸入的文本中獲取一個字符串並返回一個字符串 ,然后我需要將該字符串放入一個段落標簽中而不刷新頁面
這是我的代碼:
html頁面:
<input type="text" id="equation_input">
<input type="button" value="Calculate" id="equation_submit" onclick="fun()">
<p id="value"></p>
RESTful Web服務:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.tarek.doctorMath.resources.test.*;
@Path("/first")
public class first_equation {
@GET
@Path("/{test}")
@Produces(MediaType.TEXT_PLAIN)
public String test(@PathParam("test") String equation) {
return "test";
}
}
誰能幫我?
您正在尋找的被稱為AJAX(異步JavaScript和XML)
有很多庫可以簡化ajax,但是對於如此簡單的事情,這是一個簡單的純JS示例
//url: the url to call through ajax
//callback: a function to execute when it is done
//error: a function for if there was a problem with the request
function load(url, callback, error){
var xhr;
// here we check what version of AJAX the browser supports
if(typeof XMLHttpRequest !== 'undefined')
xhr = new XMLHttpRequest();
else {
//internet explorer is stupid...
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
function ensureReadiness() {
//not done yet
if(xhr.readyState < 4) {
return;
}
// all is well
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
} else {
error(xhr);
}
}
//here we assign the function above to check if the AJAX call is finished
xhr.onreadystatechange = ensureReadiness;
//send the request
xhr.open('GET', url, true);
xhr.send('');
}
//we call the function like this:
load('http://example.com/page',
function(successText){
//get the paragraph and assign the value
var p = document.getElementById('value');
p.innerHTML = successText;
},
function(error){
console.log(error);
})
查看此主題以獲取有關什么是AJAX的更多信息: AJAX如何工作?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.