ios - 使用JavaScript验证UIWebView表单并获取控制器中的表单字段值

时间:2012-10-11 02:01:00

标签: ios ios5 uiwebview

我有一个UIWebView,我有一个这样的简单形式:

    <form action="http://message/">Your Email: <input id="email" /><br />
        <input type="submit" value="Submit" />
    </form>

现在没有JS验证,表单只是在某处提交,我不知道如何获取字段值。我在控制器中的所有内容都是:

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{   
    if ([request.URL.scheme isEqualToString:@"message"]) 
    {
        // RIGHT NOW THIS DOESNT WORK...HOW DO I GET IT RIGHT? :)
        NSString *useremail = [theWebView stringByEvaluatingJavaScriptFromString:@"getEmail()"];
        NSLog(useremail);

    }  

    return YES;
}

我不确定如何让控制器查看字段值以及如何验证js中的字段值。

请告诉我如何最好地完成这项工作。

我还尝试创建一个JavaScript函数来简单地点击请求网址(这是我真正需要的)但是这不是发送请求网址:

    <script type="text/javascript">
    function test () 
    {
        // Het the params.
        var name = escape(document.getElementById("name").value);
        var email = escape(document.getElementById("email").value);
        var phone = escape(document.getElementById("phone").value);


        var url="http://www.myurl.com?platform=ios&name="+name+"&email="+email+"&phone="+phone;
        alert(url);




        var ajaxObj = createXMLHttp();
        //var url = 'myrequest.php';
        ajaxObj.open("GET", url, true);
        ajaxObj.onreadystatechange = function() 
        {
            ajaxObj.processRequest();
        }
            ajaxObj.send(null);

            ajaxObj.processRequest = function() 
            {
              if (this.readyState == 4) 
              {
                // got response
              }
            }


        alert("1");
        var req ;

        // Browser compatibility check                  
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {

            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {

                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }

        }


        var req = new XMLHttpRequest();
        req.open("GET", url ,true);
        req.onreadystatechange = function () 
        {
            //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
        }

        req.send(null);  

       return false;
    }
        </script>

谢谢!

1 个答案:

答案 0 :(得分:3)

这样的事情怎么样:

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{   
    if ([request.URL.scheme isEqualToString:@"message"]) 
    {
        NSString *useremail = [theWebView stringByEvaluatingJavaScriptFromString:@"escape(document.getElementById(\"email\").value);"];
        NSLog(useremail);

    }  

    return YES;
}