java远程调用Ajax接口,Java 调用 php接口(Ajax)(二)(示例代码)

由于项目里面需要用到Java调用PHP的充值接口,所以学习了一下,以下这个Demo是个小小的例子,写下来做个笔记>

jsp页面:

contentType="text/html; charset=GBK"%>

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + ":" + request.getServerPort()

+ path + "/";

%>

Lost Crown

function getXmlHttp(){

var http_request = false;

if (window.XMLHttpRequest){

http_request = new XMLHttpRequest();

if (http_request.overrideMimeType){

http_request.overrideMimeType(‘text/xml‘);

}

}else if (window.ActiveXObject){

try{

http_request = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e){

try{

http_request = new ActiveXObject("Microsoft.XMLHTTP");

}catch (e) {

}

}

}

if (!http_request){

alert("不能创建对象!");

return false;

}

return http_request;

}

function result(){

if(req.readyState == 4 && req.status == 200){

var names = req.responseText;

alert("Hello:"+names);

}

}

function checkTest(){

var name = document.getElementById("name").value;

var ul = "http://localhost:8011/TestAjax/index.php?name=" + name;

req = getXmlHttp();

req.onreadystatechange = result;

req.open("POST",ul,true);

req.setRequestHeader(‘If-Modified-Since‘, ‘0‘);

req.send(null);

}

It‘s A Ajax Test

用户名

php页面:

$username = $_REQUEST[‘name‘];

echo($username);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用 AJAX 调用 Java WebService 接口,可以按照以下步骤操作: 1. 创建一个 Java WebService,例如使用 JAX-WS 标准,可以使用 JavaEE 环境或者 Apache CXF 等开源框架。 2. 在 WebService 中定义接口方法,例如: ``` @WebService public interface HelloWorld { @WebMethod String sayHello(String name); } ``` 3. 实现接口方法,例如: ``` @WebService(endpointInterface = "com.example.HelloWorld") public class HelloWorldImpl implements HelloWorld { @Override public String sayHello(String name) { return "Hello " + name + "!"; } } ``` 4. 部署 WebService 到服务器上,例如使用 Tomcat 等 Servlet 容器。 5. 在客户端页面中使用 AJAX 调用 WebService 接口,例如: ``` $.ajax({ type: "POST", url: "http://localhost:8080/HelloWorld", data: JSON.stringify({ name: "World" }), contentType: "application/json", dataType: "json", success: function (response) { alert(response); }, error: function (xhr, status, error) { alert("Error: " + error); } }); ``` 其中,url 参数为 WebService 的访问地址,data 参数为传递给接口方法的参数,contentType 参数为请求数据的 MIME 类型,dataType 参数为响应数据的 MIME 类型。在 success 回调函数中可以处理接口方法的返回值,而在 error 回调函数中可以处理错误信息。 注意,由于 AJAX 调用涉及跨域问题,需要在服务器端设置 CORS(跨域资源共享)或者使用 JSONP(JSON with Padding)等方式解决。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值