2013-03-15 104 views
1

我想從數據庫使用web服務在asp.net 3.5 與C#和jquery移動填充列表。如何使用json從sql服務器檢索數據ASP.net

它運行良好,當我運行該網站,但是當我發佈到我的服務器它不會填充列表和ajax錯誤函數捕獲錯誤。 這是我的代碼。

我的web服務:

public class product 
{ 
    //[product] ,[img1] ,[descr] 
    public string name; 
    public string img1; 
    public string descr; 

} 

[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 CarService : System.Web.Services.WebService { 


[WebMethod] 
    public List<product> GetAllProducts() 
    { 
     List<product> productt = new List<product> {}; 

     string query = "SELECT [product] ,[img1] ,[descr] FROM [ELQ].[dbo].[products]"; 
     SqlCommand cmd = new SqlCommand(query); 
     DataSet ds = GetData(cmd); 
     DataTable dt = ds.Tables[0]; 

     // Process each employee record in table... 
     //foreach (DataRow dr in dt.Rows) 
     foreach(DataRow item in ds.Tables[0].Rows) 
     { 
      //productt.Add((DataRow) row); 
      product pro = new product(); 
      pro.name = item["product"].ToString(); 
      pro.img1 = item["img1"].ToString(); 
      pro.descr = item["descr"].ToString(); 
      productt.Add(pro); 
     } 

     return productt; 
    } 
    public static string GetShipDetails() 
    { 

     string query = "SELECT [product] ,[img1] ,[descr] FROM [ELQ].[dbo].[products]"; 
     SqlCommand cmd = new SqlCommand(query); 
     return GetData(cmd).GetXml(); 
    } 
    private static DataSet GetData(SqlCommand cmd) 
    { 
     string connString = "Data Source=GHOST-PC\\STC;Initial Catalog=ELQ;Integrated Security=True"; 
     using (SqlConnection con = new SqlConnection(connString)) 
     { 
      using (SqlDataAdapter sda = new SqlDataAdapter()) 
      { 
       cmd.Connection = con; 
       sda.SelectCommand = cmd; 
       using (DataSet ds = new DataSet()) 
       { 
        sda.Fill(ds); 
        return ds; 
       } 
      } 
     } 
    } 


} 

腳本:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
<%@ Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html> 
<head runat="server"> 
    <title>jQuery Mobile Market</title> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" /> 
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
    <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script> 
    <script type="text/javascript"> 

      $(document).on('pageinit', function() { 
       Greating(); 

      }); 

      function Greating() { 

       $.ajax({ 

        type: "POST", 
        url: "CarService.asmx/GetAllProducts", 
        data: "{}", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (response) { 

         var productt = response.d; 
         $.each(productt, function (index, product) { 

          $("#theList").append("<li><img src='pic/" + product.img1 + "'> <br /> " + product.name + " <br />" + product.descr + "</li>"); 
         }); 

         $("#theList").listview("refresh"); 
        }, 

        error: function (response) { 
         $("#theList").append("<li>error<li>"); 
        } 
       }); 
      } 
     </script> 

它接縫像JSON響應是錯誤的,併產生錯誤,但是當我從我的筆記本電腦執行的代碼,它工作正常。 我不知道我錯過了什麼,所以請幫助我。

錯誤:

POST http://192.168.1.7:7777/CarService.asmx/GetAllProducts 500 (Internal Server Error) jquery-1.8.2.min.js:2 
send jquery-1.8.2.min.js:2 
p.extend.ajax jquery-1.8.2.min.js:2 
Greating 192.168.1.7:18 
(anonymous function) 192.168.1.7:12 
p.event.dispatch jquery-1.8.2.min.js:2 
g.handle.h jquery-1.8.2.min.js:2 
p.event.trigger jquery-1.8.2.min.js:2 
(anonymous function) jquery-1.8.2.min.js:2 
p.extend.each jquery-1.8.2.min.js:2 
p.fn.p.each jquery-1.8.2.min.js:2 
p.fn.extend.trigger jquery-1.8.2.min.js:2 
a.Widget._trigger jquery.mobile-1.3.0.min.js:2 
a.widget._createWidget jquery.mobile-1.3.0.min.js:2 
(anonymous function) jquery.mobile-1.3.0.min.js:2 
a.(anonymous function).(anonymous function) jquery.mobile-1.3.0.min.js:2 
(anonymous function) jquery.mobile-1.3.0.min.js:2 
p.extend.each jquery-1.8.2.min.js:2 
p.fn.p.each jquery-1.8.2.min.js:2 
a.fn.(anonymous function) jquery.mobile-1.3.0.min.js:2 
C jquery.mobile-1.3.0.min.js:2 
a.mobile.loadPage jquery.mobile-1.3.0.min.js:2 
a.mobile.changePage jquery.mobile-1.3.0.min.js:2 
a.mobile._handleHashChange jquery.mobile-1.3.0.min.js:2 
(anonymous function) jquery.mobile-1.3.0.min.js:2 
p.event.dispatch jquery-1.8.2.min.js:2 
g.handle.h jquery-1.8.2.min.js:2 
p.event.trigger jquery-1.8.2.min.js:2 
(anonymous function) jquery-1.8.2.min.js:2 
p.extend.each jquery-1.8.2.min.js:2 
p.fn.p.each jquery-1.8.2.min.js:2 
p.fn.extend.trigger jquery-1.8.2.min.js:2 
(anonymous function) jquery.mobile-1.3.0.min.js:2 
+0

成功:功能(響應){ 的console.log(響應);通過按f12 – 2013-03-16 06:11:03

+0

執行此操作並查看您的瀏覽器控制檯它會拋出什麼錯誤? – ThinkingStiff 2013-03-16 07:29:48

+0

這是錯誤加載資源失敗:服務器響應狀態爲500(內部服務器錯誤)http:// localhost:7777/CarService.asmx/GetAllProducts POST http:// localhost:7777/CarService.asmx/GetAllProducts 500(內部服務器錯誤)jquery-1.8.2.min.js:2 發送jquery-1.8.2.min.js:2 p.extend.ajax jquery-1.8.2.min.js:2 Greating本地主機:18 (匿名函數)localhost:12 p.event.dispatch jquery-1.8.2.min.js:2 g.handle.h jquery-1.8.2.min.js:2 p.event。觸發jquery-1.8.2.min.js:2 (匿名函數)jquery-1.8.2.min.js:2 p.extend.each jquery-1.8.2.min.js – 2013-03-16 07:34:18

回答

3

我固定的錯誤,實際上它是不是一個錯誤,我不得不登錄並在我的數據庫認證的問題,所以我決定後,適合初學者的代碼和我一樣,所以這是我的代碼

首先我建了一個服務來處理我的數據庫,我用一個簡單的方法來做到這一點

這是我CarService類

using System; 
using System.Collections.Generic; 
//using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Data.SqlClient; 
//using System.Web.Script.Serialization; 
using System.Web.Script.Services; 
using System.IO; 
//using Newtonsoft.Json; 
using System.Data; 
using System.Text; 



/// <summary> 
/// Summary description for CarService 
/// </summary> 
[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 CarService : System.Web.Services.WebService { 

    public class product 
    { 
     public string name; 
     public string img1; 
     public string descr; 

    } 

    static List<product> productt = new List<product> { }; 

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    [WebMethod] 
    public List<product> GetAllProducts() 
    { 

     string query = "SELECT [product] ,[img1] ,[descr] FROM [ELQ].[dbo].[products]"; 
     SqlCommand cmd = new SqlCommand(query); 
     DataSet ds = GetData(cmd); 
     DataTable dt = ds.Tables[0]; 
     foreach(DataRow item in ds.Tables[0].Rows) 
     { 
      product pro = new product(); 
      pro.name = item["product"].ToString(); 
      pro.img1 = item["img1"].ToString(); 
      pro.descr = item["descr"].ToString(); 
      productt.Add(pro); 
     } 

     return productt; 
    } 

    private static DataSet GetData(SqlCommand cmd) 
    { 
     string connString = "Data Source=GHOST-PC\\STC;Initial Catalog=ELQ;Persist Security Info=True;User ID=sa;[email protected]"; 
     string str = "Data Source=GHOST-PC\\STC;Initial Catalog=ELQ;Persist Security Info=True;User ID=sa;[email protected]"; 
     using (SqlConnection con = new SqlConnection(str)) 
     { 
      using (SqlDataAdapter sda = new SqlDataAdapter()) 
      { 
       cmd.Connection = con; 
       sda.SelectCommand = cmd; 
       using (DataSet ds = new DataSet()) 
       { 
        sda.Fill(ds); 
        return ds; 
       } 
      } 
     } 
    } 


} 

,然後這裏是我的BAGE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<%@ Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head runat="server"> 
    <title>jQuery Mobile Market</title> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" /> 
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
    <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script> 
    <script type="text/javascript" type="text/javascript"> 


     $(document).ready(function() { 

      $("#theList").removeData(); 
      Greating(); 
     }); 

     function Greating() { 

      $.ajax({ 

       type: "POST", 
       url: "CarService.asmx/GetAllProducts", 
       data: "{}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (response) { 

        var productt = response.d; 
        $.each(productt, function (index, product) { 

         $("#theList").append("<li><img src='pic/" + product.img1 + "'> <br /> " + product.name + " <br />" + product.descr + "</li>"); 
        }); 

        console.log(response); 
       }, 

       error: function (response) { 
        $("#theList").append("<li>error<li>"); 

        console.log(response); 
       } 
      }); 
     } 
    </script> 
</head> 
<body> 
    <div data-role="page" id="homePage"> 
     <div data-role="header"> 
      <div data-role="navbar"> 
       <ul> 
        <li><a href="#homePage" class="ui-btnactive">Home</a></li> 
        <li><a href="#aboutPage">7arag</a></li> 
        <li><a href="#market">Market</a></li> 
        <li><a href="#settings">Settings</a></li> 
       </ul> 
      </div> 
     </div> 
     <div data-role="content"> 
      <form action="echo.cfm" method="post"> 
      <div data-role="fieldcontain"> 
       <label for="name"> 
        Name:</label> 
       <input type="text" name="name" id="name" value="" /> 
      </div> 
      <div data-role="fieldcontain"> 
       <label for="email"> 
        Email:</label> 
       <input type="text" name="email" id="email" value="" /> 
      </div> 
      <div data-role="fieldcontain"> 
       <input type="submit" name="submit" value="Send" /> 
      </div> 
      </form> 
     </div> 
     <div data-role="footer" data-position="fixed" dataid="footernav"> 
      <p> 
       asd</p> 
     </div> 
    </div> 
    <div data-role="page" id="market"> 
     <div data-role="navbar"> 
      <ul> 
       <li><a href="#homePage" class="ui-btnactive">Home</a></li> 
       <li><a href="#aboutPage">7arag</a></li> 
       <li><a href="#market">Market</a></li> 
       <li><a href="#settings">Settings</a></li> 
      </ul> 
     </div> 
     <div data-role="content"> 
      <ul id="theList" data-role="listview" data-inset="true" data-filter="true"> 
      </ul> 
     </div> 
     <div data-role="footer" data-position="fixed" dataid="footernav"> 
     </div> 
    </div> 
    <div data-role="footer" data-position="fixed" dataid="footernav"> 
    </div> 
    </div> 
</body> 
</html> 

,並完成..享受;)

0

您需要的byte []轉換到 「Convert.ToBase64String」 在Web服務,然後JavaScript的理解圖像串base64的形式。這裏我已經完成了我的web服務中的下面的代碼。

//MyJs Code: 
 

 
function getMyImage(id_No){ 
 
    $.support.cors= true; 
 
    $.ajax({`enter code here` 
 
     url: "http://someipaddreess/phonegap.asmx/spKP_MyImage", 
 
     contentType: 'application/json;charset=utf-8', 
 
     type: "POST", 
 
     data: JSON.stringify({CSID_NO:getCSIDNumberByFK(id_No)}), 
 
     async:false, 
 
     dataType: "json", 
 
     success : function(msg) { 
 
      var myImageStr = msg.d; 
 
      $("#testImg").attr('src','data:image/jpeg;base64,' + myImageStr); 
 
     }, 
 
     error: function(xhr, errorThrown, textStatus){ 
 
      window.alert("error: Failed to call WebService for measuring image" + " " + textStatus); 
 
     } 
 
    }); 
 
} 
 
//MyJs Code Ends here:

using System; 
 
using System.Collections.Generic; 
 
using System.Linq; 
 
using System.Web; 
 
using System.Web.Services; 
 
using Newtonsoft.Json; 
 

 
using System.Data; 
 
using System.IO; 
 
using System.Data.SqlClient; 
 
using System.Configuration; 
 
using System.Collections; 
 
using System.Drawing; 
 

 
namespace phonegap_webservices 
 
{ 
 
    /// <summary> 
 
    /// Summary description for phonegap 
 
    /// </summary> 
 
    [WebService(Namespace = "http://tempuri.org/")] 
 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
 
    [System.ComponentModel.ToolboxItem(false)] 
 
    // 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 phonegap : System.Web.Services.WebService 
 
    {     
 
     dalKPDataSQl tblKPDataSql = new dalKPDataSQl(); 
 
     dalBuilderPortal tblBuilderPortalSql = new dalBuilderPortal(); 
 

 
     [WebMethod] 
 
     public string spKP_MyImage(long CSID_NO) 
 
     { 
 
      DataTable dt = new DataTable();          
 
      dt = tblKPDataSql.dtGetInfoByCSID("SP_ImageFunCall", CSID_NO); 
 
      byte[] imageByteArray = (byte[])dt.Rows[0]["MyImage"]; 
 
      return Convert.ToBase64String(imageByteArray); 
 
     } 
 
    } 
 
}