问题
I have a form in the UIWebView to interact with a web service, when I submit the form, the data gets sent to a web service and it will return the result to another UIWebView. The two UIWebViews are under a navigation controller, so when the use submits the form, it slides to another view to display the result. Can anyone point me out how I can achieve this? What do I fill in the "action" attribute in the form element? How can I get the user input back to the application so I can use the web service? I am new to this field, any help will be appreciated. Thanks!
Update:
Is there a way to save form data from web view back to my program? I think it's better to save form data back to the program (i.e. store params into nsstring) when I click submit button, and then start querying web service.
回答1:
You can use the
stringByEvaluatingJavaScriptFromString
function for firing a javascript method from objective c and get a return value from that method.
For example
//Calling the getTheUsername in the javascript.
NSString *userName = [yourWebView stringByEvaluatingJavaScriptFromString:@"getTheUsername()"];
and in javascript
//Method in javascript
function getTheUsername()
{
return userNameVariable;
}
And I doubt that here you may wanna do vice-versa (Call obj-c method from javascript). This cannot be done directly here is the work around.
Set a UIWebViewDelegate, and implement the method webView:shouldStartLoadWithRequest:navigationType:. In your JavaScript code, navigate to some fake URL that encodes the information you want to pass to your app, like, say: window.location = "someLink://yourApp/form_Submitted:param1:param2:param3"; In your delegate method, look for these fake URLs, extract the information you need, take whatever action is appropriate, and return NO to cancel the navigation.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"%@",[[request URL] query]);
return YES;
}
回答2:
If I understood your problem correctly, I think following steps will help you to provide the solution.
- In the action of form, you need to write the URL to the web service.
- In your form, the name of the input field should be matched with the name of the parameters expected for the web service.
- In your first UIWebView Navigation control, Create the object of screen having second UIWebView and set the response of the web service to the instance member of the object.
- In your first UIWebView Navigation control, you need to write
[self presentModalViewController:webView2Object animated:YES]; - In the screen of having webView2, parse the response before loading the second UIWebView. and inject it with the displayed page using javascript.
来源:https://stackoverflow.com/questions/7466875/submit-a-form-in-uiwebview