1.定义一个宏
#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();\
}"
2.参数
NSDictionary *dataDic = @{@"username":@"shaotang"};
把参数转为JSON字符串
NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
NSString *postData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
3.最后
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,ScreenHeight)];
NSString *_url = @"http://";
NSString * js = [NSString stringWithFormat:@"%@my_post(\"%@\", %@)",POST_JS, _url, postData];
// 执行JS代码
[_webView evaluateJavaScript:js completionHandler:^(id object, NSError * _Nullable error) {
}];
[self addSubview:_webView];