本文目錄一覽:
如何在Java項目中使用Ajax?
如果要使用ajax,必須要導入相應的jquery.js等才可以用。具體用法如下:
$.ajax({
type: “GET”,
url: “test.json”,
data: {username:$(“#username”).val(), content:$(“#content”).val()},
dataType: “json”,
success: function(data){
alert(data.status);
});
});
ajax技術適用於在頁面不刷新的情況下前後台數據的動態數據交互。
學java ajax重要不
如果做JAVA Web的話,Ajax非常重要,這是web的基礎,如果你做JAVASE或者是純JAVA後端,不涉及web相關的東西,就無所謂了,但是最好也了解一下,對你以後的發展還是很有必要的
java 怎麼向ajax返回數據
直接PrintWriter out = response.getWriter();
out.write(“這是要返回的數據”);
這樣就可以了啊
JAVA的ajax方法?
//方式一:使用post請求的方式,不通過url傳參,採用data傳參
$.ajax({
url:”userAction_findMangerByDeptId”,//訪問的地址
type:”post”,
data:{“傳遞到後台的參數名”:參數},
dataType:’text’,//後台返回的數據格式類型
success:function(data){
})
}
})
}
//方式二:這是get提交方法,會出現中文亂碼,所以要 1.先將數據轉碼
參數名 = encodeURI(encodeURI(要轉的參數));
$.ajax({
url:”userAction_findMangerByDeptId?參數名”+參數值,
type:”get”,
dataType:’text’,//後台返回的數據格式類型
success:function(data){
})
}
})
}
2.後台接收前端傳遞內容後要進行解碼
String 參數名 = URLDecoder.decode(接收的參數);
如何用JAVA爬取AJAX加載後的頁面
普通的爬取是抓不了js的之後的數據的 可以用phantomjs或者htmlUnit實現
附上phantomjs示列代碼
package cn.wang.utils;
import java.util.Random;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
public class htmlUnitUtils {
static WebClient webClient = null;
static Random random = new Random();
static{
//1.創建對象
webClient = new WebClient(BrowserVersion.CHROME);
//2.設置參數
//啟動js
webClient.getOptions().setJavaScriptEnabled(true);
//關閉css渲染
webClient.getOptions().setCssEnabled(false);
//啟動重定向
webClient.getOptions().setRedirectEnabled(true);
//設置連接超時時間 ,這裡是10S。如果為0,則無限期等待
webClient.getOptions().setTimeout(1000 * 15);
//啟動cookie管理
webClient.setCookieManager(new CookieManager());
//啟動ajax代理
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
//js運行時錯誤,是否拋出異常
webClient.getOptions().setThrowExceptionOnScriptError(false);
//設置瀏覽器請求信息
webClient.addRequestHeader(“Accept”, “text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”);
webClient.addRequestHeader(“Accept-Encoding”, “gzip, deflate”);
webClient.addRequestHeader(“Accept-Language”, “zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2”);
webClient.addRequestHeader(“Connection”, “keep-alive”);
webClient.addRequestHeader(“Upgrade-Insecure-Requests”, “1”);
}
public static void runJs(String url){
try {
webClient.addRequestHeader(“User-Agent”, Constant.useragents[random.nextInt(Constant.useragents.length)]);
//等待js渲染執行 waitime等待時間(ms)
webClient.waitForBackgroundJavaScript(1000 * 10);
//3.獲取頁面
webClient.getPage(url);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(webClient != null){
webClient.close();
}
}
}
public static void main(String[] args) {
runJs(“”);
System.setProperty(“phantomjs.binary.path”, “D:\\works\\tool\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe”);
}
}
原創文章,作者:VAIU,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/144103.html