我尝试为我的POST请求创建一个帮助程序类,并希望返回响应。但是,由于post请求是异步的,这让我感到有些困惑。
我尝试返回NSString,但它不允许我返回<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8"/>
<style>
textarea {
width: 90%;
height: 300px;
border-radius: 12px;
}
form {
max-width: 50%;
top: 10px;
bottom: 10px;
padding: 1%;
margin: auto;
height: 880px;
background: radial-gradient(#888, #999, #aaa, #bbb, #ccc, #ddd, #eee);
}
label[for=description] {
display: block;
}
body {
background: steelblue;
}
</style>
</head>
<body>
<form>
<label for="name">Name:</label>
<input id="name" name="name"/>
<hr/>
<label for="description">Description:</label>
<textarea id="des" name="cost"></textarea>
<hr/>
<button onclick="sendData()">Create Class</button>
</form>
<script>
var n;
var descript;
function sendData() {
n = document.getElementById("name").value;
descript = document.getElementById("des").value;
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
response(http.responseText);
}
};
http.open("GET", "class_add.php?name=" + name + "&descript=" + descript, true);
http.send();
}
/*This is supposed to make the display msg*/ function response(txt) {
var p = document.createElement("p");
p.innerHTML = txt;
p.style.fontSize = "30px";
p.style.fontFamily = "Comic Sans MS";
p.style.color = "magenta";
document.body.appendChild(p);
}
</script>
</body>
</html>
和response
。它只是让我放responseString
。我尝试使用return "A"
,但无法使其正常工作。
制作这样的辅助方法的正确方法是什么? (如果我在收到回复后进行检查,并且根据回复返回true或false,那也没关系)
-> NSURLResponse
答案 0 :(得分:5)
由于dataTaskWithRequest
是异步的,因此函数将在执行完成块之前命中return语句。你应该做的是为你自己的帮助器方法设置一个完成块,或者将某种委托对象传递给该函数,以便你可以调用它上面的方法让它知道webservice回调的结果是什么。 / p>
以下是使用完成块的示例:
class func hello(name: String, completion: (String? -> Void)){
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "Hi, \(name)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
completion(responseString);
}
task.resume()
}
然后使用它
<#YourClass#>.hello("name") { responseString in
//do something with responseString
}
没有测试代码,但应该是正确的