2014年4月29日 星期二

[EFGP] FormScript with jQuery

今天在測試 EasyFlow GP 透過 jQuery 使用 C# 寫的 Webservice

在 VisualStudio 中用 c# 寫的程式可以正常呼叫,但是透過 EFGP 就不能
試了半天之後終於得到答案了,在這裡做個筆記

1. jQuery.noConflict(); //避免 $ 與其他 jQuery UI 的衝突 ,在這個範例上沒有設也ok
2. jQuery.support.cors = true; // 跨網域要把它設為 true , 就是這一點搞了非常久

範例如下:

FormScript :

document.write('<script type="text/javascript" src="../../js/jquery-1.7.1.min.js"></script>');

 
function GetInfo() {
  //jQuery.noConflict(); 
  jQuery.support.cors = true;
  //var jq = jQuery.noConflict();
       var $res;
       $.ajax({
           type: "POST",
           url: "http://10.1.10.103:8888/JsonServiceSample.asmx/GetOneUserInfo",
           contentType: "application/json; charset=utf-8",
           async: false,
           cache: false,
          dataType: 'json',
          data: "{name:'Test',age:29}",
          success: function (data) {
              if (data.hasOwnProperty("d")) {
                  $res = data.d;
              }
              else
                  $res = data;
          },
          error: function (xhr, ajaxOptions, thrownError) {
         alert('WS status = ' + xhr.status );
         alert('WS Error =' + thrownError);
        }
      });
      return $res;
  }


function btnEdit_onclick() {
    var res = GetInfo();

    alert(res.Name);
    alert(res.Age);
}



WebService




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Services.Protocols;    //加上這個預備給 Java Call

namespace JQueryWebService
{

    public class User
    {
        public string Name { get; set; }

        public int Age { get; set; }

    }

    /// <summary>
    /// 移除 NameSpace
    /// 每一個 Methods 上面必須加上 
    /// [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    /// </summary>
    [WebService(Namespace = "", Description = "For Donma Test")]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class JsonServiceSample : System.Web.Services.WebService
    {
        [WebMethod]
        [SoapRpcMethod(Use = System.Web.Services.Description.SoapBindingUse.Literal)] 
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUserInfoString(string name, int age)
        {
            return name + "," + age;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public User GetOneUserInfo(string name, int age)
        {
            return (new User { Name = name, Age = age });
        }


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public User[] GetUsers(string name, int age)
        {
            List<User> res = new List<User>();
            res.Add(new User { Name = name + "1", Age = age });
            res.Add(new User { Name = name + "2", Age = age });

            return res.ToArray();
        }
    }
}