2012-03-31 5 views
1

PhoneGap을 사용하여 Windows Phone 7 앱을 개발 중입니다. JSON 문자열로 하위 개체 목록 (사회 복지사의 연구 프로젝트)을 반환하는 webservice를 호출하려고합니다. 이것은 내가 지금까지있어 무엇 :jQuery Mobile을 사용하여 웹 서비스에 액세스하기

 <!DOCTYPE html> 
<html> 
    <head> 
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" /> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> 

    <title>Login Page</title> 

     <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title" charset="utf-8"/> 

     <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script> 
     <script type="text/javascript"" src="../Scripts/jquery.mobile-1.0.1.js"></script> 

     <script type="text/javascript"> 

      document.addEventListener("deviceready", onDeviceReady, false); 

      // once the device ready event fires, you can safely do your thing! -jm 
      function onDeviceReady() { 

      } 

      function LoginButton_onclick() { 
      var email=document.getElementById("EmailBox").value; 
      var pass=document.getElementById("PasswordBox").value; 
      $.ajax({ 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       url: "http://localhost:56018/PhoneWebServices.asmx?op=GetMyChildren", 
       data: '{ "email" : "' + email + '", "password": "' + pass + '" }', 
       dataType: "json", 
       success: GetChildrenSuccess, 
       failure: GetChildrenFailed 
      }); 
     } 

     function GetChildrenSuccess(response) { 
      var children = eval('(' + response.d + ')'); 
      var child; 
      for(child in children) { 
       document.getElementById('ResultsDiv').innerHTML = "ID: "+child.ID+ " Name: "+child.Name+" Surname: "+child.Surname+" \r\n"; 
      } 
     } 

     function GetChildrenFailed(error) { 
      document.getElementById('ResultsDiv').innerHTML = "Error"; 
     } 
     </script> 

    </head> 
    <body> 
    <h1>Please Login:</h1> 

    <div id="LoginDiv"> 
     Email: <input id="EmailBox" type="text" /><br /> 
     Password: <input id="PasswordBox" type="password" /><br /> 

     <input id="LoginButton" type="button" value="Submit" onclick="LoginButton_onclick()" /> 
    </div> 
    <div id="ResultsDiv"> 
    </div> 
    </body> 
</html> 

웹 서비스 :

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService] 
public class GetChildren : System.Web.Services.WebService { 

public GetChildren() { 

    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
} 

MD5 md5Hash = MD5.Create(); 
    string conString = ConfigurationManager.ConnectionStrings["SponsorChildDatabase"].ConnectionString; 

    [WebMethod(Description = "Returns the list of children for whom the social worker is responsible.")] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public String GetMyChildren(String email, String password) 
    { 
     DataSet MyChildren = new DataSet(); 

     int ID = SocialWorkerLogin(email, password); 
     if (ID > 0) 
     { 
      MyChildren = FillChildrenTable(ID); 
     } 
     MyChildren.DataSetName = "My Children"; //To prevent 'DataTable name not set' error 

     List<Child> children = new List<Child>(); 
     foreach (DataRow rs in MyChildren.Tables[0].Rows) 
     { 
      Child c=new Child(rs["Child_ID"].ToString(), rs["Child_Name"].ToString(), rs["Child_Surname"].ToString()); 
      children.Add(c); 
     } 

     // Return JSON data 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     string strJSON = js.Serialize(children); 
     return strJSON; 
    } 

아이 클래스 :

public class Child 
{ 
    String id; 

    public String ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 
    String name; 

    public String Name 
    { 
     get { return name; } 
     set { name = value; } 
    } 
    String surname; 

    public String Surname 
    { 
     get { return surname; } 
     set { surname = value; } 
    } 

    public Child(String Cid, String Cname, String Csurname) 
    { 
     this.ID = Cid; 
     this.Name = Cname; 
     this.Surname = Csurname; 
    } 
} 

나는 그것의 자신의 웹 서비스를 테스트

(즉,이 입력 내 일반 브라우저에서 URL을) 작동하지만, 제출 버튼을 누르면 내 모바일 애플 리케이션에서 아무것도하지 않습니다.

이것은 내 첫 모바일 앱이므로 제대로 디버깅하는 방법을 모르거나 전혀 문제가없는 것 같아서 문제가 무엇인지 모릅니다. 아마 웹 서비스가 IIS에서 호스팅되어야한다고 생각하지만, 서비스 참조를 추가 할 수 있기 때문에 찾은 것 같습니다. 어떤 아이디어가 문제가 될 수 있습니다/내 접근 방식이 맞다면?

+0

버튼에 클릭 이벤트를 연결하는 위치가 표시되지 않습니다. 당신은 처리기를 가지고 있지만, 보여준 코드를 기반으로하지 않습니다. – Alex

+0

좋아, HTML의 나머지 부분을 추가하면 자바 스크립트 함수에 단추를 연결하는 방법이 아닙니까? – Matt

답변

2

나는 당신의주의를 끌고 싶은 몇 가지 이슈를 보았다. 이미 jQuery를, $ ('# 아이디')를 사용하고 있기 때문에

  1. 가에서 getElementById를 사용하지 마십시오 훨씬 낫다.

  2. $ .ajax 메소드에 데이터를 게시하는 경우, 자체에서 문자열 객체를 생성하는 대신 JSON.stringify (데이터)를 사용하는 것이 훨씬 더 좋습니다.

  3. 콜백 함수에서 결과의 평가 결과가 잘못되었지만 잘못되었습니다. jQuery는 초기 평가를 수행합니다. 웹 서비스를 잘못 사용하고 있기 때문에 그렇게해야합니다. 결코 당신의 곁에서 json serialization을하지 말고 결코 문자열을 반환하지 마십시오. 대신 객체를 반환하면 ASMX가 자동으로 직렬화를 수행합니다.

불행히도 질문이 구체적이지 않으므로 답변하기가 어렵습니다. 앱은 웹 모바일 앱이므로 브라우저에서 바로 시작할 수 있습니다. FireBug 또는 Chrome 개발 도구를 사용하여 JS를 디버그하고 잘못된 것을 확인하십시오. Visual Studio를 사용하여 서비스 코드를 디버깅하십시오.

+0

제게 많은 도움을 주었고 적어도 문제를 발견 할 수있었습니다. – Matt

+0

@Matt, 같은 문제를 가진 다른 사람들이 당신이 한 일을 볼 수 있도록 솔루션을 게시 할 수 있습니까? – jlafay

+0

안녕하세요 알렉산더 .. 나는 당신의 대답에 대해 질문 할 것입니다! 당신의 대답 3 var 자식 = eval ('('+ response.d + ')'); 잘못된 것이고 jQuery는 당신을 위해 초기 평가를 수행한다! 이것은 무엇을 의미 하는가? – Mehmet

관련 문제