這是一個非常小的錯誤,我已經嘗試了幾個小時。
考慮到這段代碼
using System;
public partial class Controls_DashboardGraph : InboundOutboundControl
{
public string GraphTitle
{
get
{
if (2>1) //To simply the logic, it will always meets this condition
{
return "The World";
}
else
{
return "All Cocoms";
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Somelogic here
}
}
它有一個GraphTitle變數。
我正在嘗試使用首頁的值來執行在線字串連接
<%@ control language="C#" autoeventwireup="true" codefile="DashboardGraph.ascx.cs" inherits="Controls_DashboardGraph" %>
<script type="text/javascript">
var title = <%= this.GraphTitle%>;
var isInBound = "true";
<%
if (3>2) //To minimize the code, simply the logic here
{
%>
path = `Services/ChartData.asmx/RetrieveChart?title=${title}&inbound=${isInBound}`;
<%
}
else
{
%>
isInBound = "false";
path = `Services/ChartData.asmx/RetrieveChart?title=${title}&inbound=${isInBound}`;
<%
}
%>
$.ajax({
type: "GET",
url: path,
success: function (data) {
//DoSomething
}
});
</script>
我正在嘗試連接字串以獲取路徑,以便可以在 ajax 中使用。但是,當我這樣做時,我得到了
'未捕獲的語法錯誤:意外的識別符號'世界'
上線var title = <%= this.GraphTitle%>;
;
我試過的:
1:我認為是因為字串中的空格。但是,當我將回傳值更改為“TheWorld”時,我得到了
未捕獲的參考錯誤:未定義 TheWorld
2:我試過不同的蜂蜇:<%# %>,也沒有用。
我需要幫助: 我知道這是一個非常微不足道的錯誤,但我已經被它困擾了一段時間。這里有什么問題?為什么這只是字串連接拋出錯誤?
uj5u.com熱心網友回復:
改變這個:
var title = <%= this.GraphTitle%>;
對此:
var title = "<%= Regex.Escape( this.GraphTitle ) %>";
- 注意兩點:
- 外部雙引號
"
。 - 使用
Regex.Escape
作為窮人的替代品將記憶體中的 .NETString
字符轉換為轉義的 JavaScript 字串,因為 JavaScript 和 .NET 正則運算式共享許多轉義序列(盡管這種方法并不完美,但它可以在緊要關頭作業)。- 因此,如果
GraphTitle
包含雙引號字符,那么它將呈現為 JS 轉義引號,因此您的 JS<script>
元素不會出現亂碼。
- 因此,如果
- 外部雙引號
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525631.html
下一篇:MVC表單資料無法系結到模型