转载自:https://www.jianshu.com/p/866847bd139a
一、先定义一个JS代码的宏
#define POST_JS @"function my_post(path, params) {
var method = "POST";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
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();
}"
二、在viewDidLoad里这样写
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
WKWebView * myWeb = [[WKWebView alloc] initWithFrame:self.view.frame ];
self.myWeb = myWeb;
[self.view addSubview:myWeb];
// 要传递的参数,(在开发中可以字典转成json字符串即可)
NSString * dataStr = @"{"token":"cac6af340960485aa334416c8a34ddbf"}";
// 发送的地址
NSString * url = @"http://192.168.1.36:8000/show_meta/";
// 最终要执行的JS代码
NSString * js = [NSString stringWithFormat:@"%@my_post("%@", %@)",POST_JS,url,dataStr];
// 执行JS代码
[myWeb evaluateJavaScript:js completionHandler:nil];
}