[英]Cannot pass string value from c# to JavaScript using JSON
我正在使用Windows Phone的Apatch Cordova插件開發WindowsPhone App。 我需要將參數從C#層傳遞給JavaScript層,然后使用c#層中的PluginResult和格式化的字符串,並在JavaScript層的cordovaCommandResult插件中使用JSON.parse()函數(cordova.js文件。)但是,當嘗試傳遞字符串值時,發生異常“語法錯誤:無效字符”。
如何傳遞字符串值,以便JSON.parse()將成功解析它?
這是我的代碼:
C#層:
public void GetConfiguration(string sensorName)
{
PluginResult result = new PluginResult(PluginResult.Status.OK,GetConfiguration());
DispatchCommandResult(result);
}
public override string GetConfiguration()
{
string config = String.Format("\"unit\":{0},\"exponent\":{1},\"frequency\":{2}",
unit,
exponent.ToString("0.0", CultureInfo.InvariantCulture),
frequency.ToString("0.0", CultureInfo.InvariantCulture));
return "{" + config + "}";
}
其中unit是一個字符串變量,它會導致異常。
JavaScript層:cordova.js
調用GetConfiguration函數:
getConfiguration: function (successCallback, errorCallback, args) {
var win = function (result) {
successCallback(result);
};
var fail = errorCallback && function (code) {
errorCallback(code);
};
exec(win, fail, "SensorsManager", "GetConfiguration", args);
},
解析從c#層返回的結果:
define("cordova/plugin/windows8/CordovaCommandResult", function (require,exports,
module) {
var cordova = require('cordova');
var channel = require('cordova/channel');
// singular WP callback function attached to window,
//status is used to determine if it is a success or error
module.exports = function (status, callbackId, args, cast) {
if (status === "backbutton") {
// do not detach backbutton event, as we need to be able to catch exceptions
cordova.fireDocumentEvent("backbutton", undefined, true);
return "true";
}
else if (status === "resume") {
cordova.fireDocumentEvent('resume');
return "true";
}
else if (status === "pause") {
cordova.fireDocumentEvent('pause');
return "true";
}
var parsedArgs;
try {
parsedArgs = JSON.parse(args);
}
catch (ex) {
return;
}
var safeStatus = parseInt(status, 10);
if (safeStatus === cordova.callbackStatus.NO_RESULT ||
safeStatus === cordova.callbackStatus.OK) {
cordova.callbackSuccess(callbackId, parsedArgs, cast);
}
else {
cordova.callbackError(callbackId, parsedArgs, cast);
}
};
});
實際上您創建的JSON是不正確的。首先使用jsonlint.com驗證您准備的JSON
更重要的一點是:1)您作為響應發送回的內容類型是什么。如果您使用第三方庫創建Json,然后直接從服務器以text / json的形式發送內容類型,則更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.