2010-12-17 17 views
17

JQuery/JSONを使用してWCF RESTを消費することに関する多くの投稿がありますが、動作させることはできません。私は現在、日付パラメータに固執しています。以下は日付を使用してWCF RESTにJQuery JSONを送信

[OperationContract] 
[WebInvoke] 
[TransactionFlow(TransactionFlowOption.Allowed)] 
string GoodRegister(DateTime pDtTimeStampTransac, Int32 pIDResource, Decimal pQty, enQtyLogType pQtyGoodLogType); 

私のJavaScriptコードです::以下は私のC#の方法がある私の最初の問題は、私は日付のシリアル化のエラーを取得しておくことである

/// <reference path="../Scripts/jquery-1.4.1-vsdoc.js" /> 
/// <reference path="json.js" /> 

Date.prototype.toMSJSON = function() { 
    var date = '\\\/Date(' + this.getTime() + ')\\\/'; 
    return date; 
}; 

function botaoclick() { 
    var date = new Date().toMSJSON(); 
    var datavar = { 
    'pDtTimeStampTransac': date, 
    'pIDResource': 1, 
    'pQty': 1 
    }; 
    $.ajax(
    { 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "http://desk01:9876/ShopFloorService/script/GoodRegister", 
    dataType: "json", 
    data: JSON.stringify(datavar), 
    //data: '{"pDtTimeStampTransac":date, "pIDResource":"teste", "pQty":"3"}', 
    error: jqueryError, 
    success: function (msg) { 
     alert("back"); 
     var divForResult = document.getElementById("test"); 
     divForResult.innerHTML = "Result: <b>" + msg.d + "</b>"; 
    } 
    } 
) 
} 

function jqueryError(request, status, error) { 
    alert(request.responseText + " " + status + " " + error); 
} 

{"ExceptionDetail":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":null,"Message":"DateTime content '\\\/Date(1292616078638)\\\/' does not start with '\\\/Date(' and end with ')\\\/' as required for JSON.","StackTrace":" at System.Runtime.Serialization.Json.JsonReaderDelegator.ParseJsonDate(String originalDateTimeValue)\u000d\u000a at 

それはdoesnの言います開始/終了の方法を開始/終了しません。

私の2番目の質問は、列挙子に乗る必要がありますか、それを送信する方法はありますか?

答えて

41

私はたくさんの髪を引き出し、これ以上の涙を流しましたが、これはうまくいきました。 の日付の書式をMSJSONに変更しました。 WCFはRick Strahlのおかげで実現したこの形式を受け入れます。

Date.prototype.toMSJSON = function() { 
    var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE 
    return date; 
}; 

ので、また、UTC時刻に日付を変換する必要があるか、面白いもののすべての種類を取得:

var dt = ...; 
    var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds())); 
    var wcfDateStr = dt1.toMSJSON(); 

・ホープ、このことができます。

jsonData = JSON.stringify([new Date()], 
    function (k, v) { return this[k] instanceof Date ? '/Date(' + v + ')/' : v; }); 

私のためにIE、クロム、およびFirefoxの最新で動作します。

+2

ああ、大丈夫だよ。ありがとう! –

+0

匿名ユーザーがthis.getUTCOffset()をプロトタイプコードに追加することを提案しました – mplungjan

2

によると:http://msdn.microsoft.com/en-us/library/bb412170.aspx

DateTime Wire Format

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

When serializing DateTime, Local and Unspecified times are written with an offset, and Utc is written without.

The ASP.NET AJAX client JavaScript code automatically converts such strings into JavaScript DateTime instances. If there are other strings that have a similar form that are not of type DateTime in .NET, they are converted as well.

The conversion only takes place if the "/" characters are escaped (that is, the JSON looks like "\/Date(700000+0500)\/"), and for this reason WCF's JSON encoder (enabled by the WebHttpBinding) always escapes the "/" character.

あなたの列挙子は問題ないはずです。

+0

私は同意します...しかし、それは動作していません...私はあきらめて、文字列のインターフェイスを変更しました。奇妙なことは、それは正しいと思われ、すべてが大丈夫だということですが、私はまだエラーがありました。 – Pascal

0

は、ここでは、JSON.stringify(とクライアントに置くところThis post(修正)から主にシームレスソリューション)です。

JSON.stringify(ネイティブメソッド)と、enumを変換するヒントのreplacerパラメータを確認してください。

0

Alsalaam Aleykum。

エラーに応答するだけです。 jsonがWebサービスにそれを解析できるように、日付形式を変更することを意味します。 WCFに渡す前に適切に日付をフォーマットするための一般的な方法があるはず

 function botaoclick() { 
 

 
     var date = new Date(); 
 
     date = "\/Date(" + date.valueOf() + ")\/"; 
 
     // valueOf() method Returns the primitive value of a Date object. 
 

 
     var datavar = { 
 
      'pDtTimeStampTransac': date, 
 
      'pIDResource': 1, 
 
      'pQty': 1 
 
     }; 
 

 
     $.ajax({ 
 
      type: "POST", 
 
      contentType: "application/json; charset=utf-8", 
 
      url: "YOUR URL", 
 
      dataType: "json", 
 
      data: JSON.stringify(datavar), 
 
      error: jqueryError, 
 
      success: function(msg) { 
 
      alert("back"); 
 
      var divForResult = document.getElementById("test"); 
 
      divForResult.innerHTML = "Result: <b>" + msg.d + "</b>"; 
 
      } 
 
     }) 
 
     } 
 

 
     function jqueryError(request, status, error) { 
 
     alert(request.responseText + " " + status + " " + error); 
 
     }

0

あなたのコードは次のようになります。

方法は次のようになりますあなたが投稿する場合

var dateToWcf = function(input) 
{ 
    var d = new Date(input); 
    if (isNaN(d)) return null;  
    var formattedDate = { date : "/Date(" + d.getTime() + ")/" }; 
    return formattedDate; 
} 

しかし、今、それはあなたが投稿しているところから、実際のタイムゾーンに基づいてオフセット値を追加します。だからこれを避けるためには、それに応じてオフセットを調整することができます。上記@vasによって答えを超える

var formattedDate = { date: "/Date(" + d.getTime() + d.getGMTOffset() + ")/" }; 
0

ビル: -

// OrderRecievedDateTime is a proper date string 
var tStart = new Date(OrderRecievedDateTime); 
// Get date in UTC (required for WCF) as morning 
var start = new Date(Date.UTC(tStart.getFullYear(), tStart.getMonth(), tStart.getDate(), 0, 0, 0)); 
// Get the ticks 
var startTicks = start.getTime(); 

// Now build the JSON param (**notice I am passing the date value as a string, by including within quotes. Without this it doesn't takes it**). 
var paramRequest = '{ "request": { "StartDate":"' + '\/Date(' + startTicks + ')\/"' + ' } }'; 

// Hit ajax, no need of any JSON.parse or stringify 
$.ajax({ ..., data = paramRequest ..}); 

WCFは適切な形式で日付を受け取ります。重要な追加はJSONの日付を文字列として渡す方法です。キーと日付文字列の組み合わせでさらに簡略化することができます

var paramRequest = '{ "request": { "StartDate":"\/Date(' + startTicks + ')\/" } }'; 
関連する問題