【问题标题】:How to call a RESTful web service's function from an html page by javascript如何通过 javascript 从 html 页面调用 RESTful Web 服务的功能
【发布时间】:2017-05-05 18:08:57
【问题描述】:

我有一个 RESTful 网络服务 (java),我想通过提交按钮向网络服务发送一个获取请求。

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 网络服务:

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";
    }
}

谁能帮帮我?

【问题讨论】:

标签: javascript java html web-services rest


【解决方案1】:

您要查找的内容称为 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 的更多信息:How does AJAX work?

【讨论】:

  • 我在哪里写这段代码?在新班还是别的什么?
猜你喜欢
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2011-08-28
  • 2011-08-28
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
相关资源
最近更新 更多