WKWebView執行Post請求

方法一:
使用js的form表單發送post請求
首先定義js函數的字符串宏

#define KWKWebViewPost_JS @"function wkwebview_post(path, enctype, params) {\
var method = \"POST\";\
var form = document.createElement(\"form\");\
form.setAttribute(\"method\", method);\
form.setAttribute(\"action\", path);\
form.setAttribute(\"enctype\", enctype);\
for(var key in params){\
    if (params.hasOwnProperty(key)) {\
        var hiddenFild = document.createElement(\"input\");\
        hiddenFild.setAttribute(\"type\", \"hidden\");\
        hiddenFild.setAttribute(\"name\", key);\
        hiddenFild.setAttribute(\"value\", params[key]);\
    }\
    form.appendChild(hiddenFild);\
}\
document.body.appendChild(form);\
form.submit();\
}"

執行使用

NSString *jsString = [NSString stringWithFormat:@"%@wkwebview_post(\"%@\", \"%@\", %@)",KWKWebViewPost_JS,@"https://www.baidu.com",@"application/x-www-form-urlencoded",@""];
[webview evaluateJavaScript:jsString completionHandler:nil];
// 測試js的html
<!DOCTYPE html>
<html>  
<head> 
<meta charset="utf-8"> 
<title>菜鳥教程(runoob.com)</title> 
</head>
<body>

<p>來調用帶參數的函數。</p>
<button onclick='wkwebview_post("http://baidu.com", "application/x-www-form-urlencoded", )'>點擊這里</button>
<script>
function wkwebview_post(path, enctype, params)
 {var method = "POST";
 var form = document.createElement("form");
 form.setAttribute("method", method);
 form.setAttribute("action", path);
 form.setAttribute("enctype", enctype);
 for(var key in params){    
    if (params.hasOwnProperty(key)) {        
        var hiddenFild = document.createElement("input");        
        hiddenFild.setAttribute("type", "hidden");        
        hiddenFild.setAttribute("name", key);        
        hiddenFild.setAttribute("value", params[key]);    
    }    
    form.appendChild(hiddenFild);
 }
 document.body.appendChild(form);form.submit();
}
</script>

</body>
</html>

方法二:
1.使用原生或AFNetworking發送post請求到服務器
2.獲取服務器返回的HTML數據,使用WKWebview加載

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。