簡體   English   中英

將URL作為字符串傳遞-'&'之后的所有內容都會丟失

[英]Passing URL as string — everything after '&' gets lost

我有一個MVC應用程序,該應用程序在onclick事件中進行API調用

<a href="javascript://" onclick="@Model.MyApiCall"></a>

@ Model.MyApiCall是一個看起來像這樣的字符串:

window.location = 'http://localhost/myPath?myImagePath=http://myimagepath&width=360&category=2'

這成功調用了我的API。 到現在為止還挺好。 但是,由於某些原因,&之后的所有內容都將從myImagePath中斷開。 因此,我得到的不是代替myImagePath等於點擊所發送的內容:

http://myimagepath

您必須對查詢字符串參數進行編碼。 您可以在javascript中完成此操作:

window.location = 'http://localhost/myPath?myImagePath=' + encodeURIComponent('http://myimagepath') + '&width=360&category=2'

使用encodeURIComponent

您也可以僅在HttpUtility.UrlEncodehttp://myimagepath Model.MyApiCall部分使用HttpUtility.UrlEncode在MVC控制器內執行此Model.MyApiCall

[編輯]

如果您的myImagePath參數是整個http://myimagepath&width=360&category=2字符串,那么Steve Danner當然是正確的,您應該遵循他的回答。

“&”號是一個特殊字符,需要進行編碼才能被瀏覽器正確解析。 您需要將查詢字符串和實際路徑分解為單獨的字符串。 像這樣:

<a href="javascript://" onclick="@(Model.MyApiCallPath +
 HttpUtility.UrlEncode(Model.MyApiCallQueryString))"></a>

您的最終js如下所示:

window.location = 'http://localhost/myPath?myImagePath=http%3A%2F%2Fmyimagepath%26width%3D360%26category%3D2';

您正在嘗試將url作為url參數傳遞。 由於相關網址包含特殊字符,因此您需要對uri組件進行轉義/編碼。

由於使用的是ASP.Net,因此應使用以下命令包裝字符串:

window.location = Uri.EscapeUriString('http://localhost/myPathmyImagePath=http://myimagepath&width=360&category=2')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM