嗨,我基本上是Ajax的新手,并且很难写出来。
我想将src值分配给从数据库中提取的Iframe 表是HobbyMasters
HobbyName
HobbyUrl
当我点击显示为链接的Hobbyname时,我写了一个函数并从表中获取url我希望该URL在iframe中加载。
最初我写了一个javascript:
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
$('iframe').attr('src', "Dancing");
});
}); </script>
但是这里src是静态的并且通过javascript我无法将数据库中的获取值分配给src属性
所以想到编写Ajax ..
我尝试了一些但是不完整。请帮助我:
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '@Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl ,
data: { data: filename },
success: function (returndata) {
Here i want to assign the fetched src from function FetchUrlByHobbyName to Iframe src
$('iframe').attr('src', filename);
}
});
});
Controller内部的功能:
[HttpPost]
public ActionResult FetchUrlByHobbyName(string Hobbyurl)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(Hobbyurl);
string url=hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(new{src=url});
return View();
}
答案 0 :(得分:0)
如果@Url.Action("FetchUrlByHobbyName")
返回业余爱好的网址,则可以
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '@Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl ,
data: { data: filename },
success: function (returndata) {
Here i want to assign the fetched src from function FetchUrlByHobbyName to Iframe src
$('iframe').attr('src', returndata);
}
});
});
最好的方法是返回与json关联的数据并从json对象获取url
success: function (returndata) {
jsonObj = jQuery.parseJSON( returndata)
$('iframe').attr('src', jsonObj.url);
}