我可以通过链接回复javascript而不是HTML吗?

I have lot of HTML pages containing links to same URL address like this:

<a href="http://example.com/page.php?params=1">Link</a>

The question is: Can I return a javascript response instead of plain HTML that can be executed by clicking on a link?

For example, I tried this in page.php:

header("Location: javascript:alert(1)", true, 302);

but it doesn't work. If I send the HTML page containing the required javascript, then the browser opens a new page or replaces the current page with this blank page containing the JS.

Is there any other method to do this without changing link's href? It seems like it can't because of security restrictions.

dongxie8856
dongxie8856 请接受我的回答
5 年多之前 回复
dsf55s1233
dsf55s1233 或者您是在询问如何在页面加载时调用javascript,或者您是否在询问如何使用javascript加载新页面?
5 年多之前 回复
dsghpgmay31938863
dsghpgmay31938863 你在问如何使用ajax吗?
5 年多之前 回复
duanrenchuo9244
duanrenchuo9244 那么响应页面可能包含在页面加载时运行的javascript,但这仍然意味着需要打开一个新页面。如果您希望当前页面执行JS,那么您需要有一个获取链接页面响应的函数,并运行它(可能使用eval()但我从来没有要求这样做,所以不确定它是多么明智是)
5 年多之前 回复

1个回答



不,你不能从服务器端调用JavaScript。 但是,您可以加载JavaScript以调用服务器并检索数据。</ p>

考虑到这一点,您可以调用从有效负载的服务器检索JSON或XML 可以通过已在客户端定义的JavaScript函数提取的驻留。</ p>

  //注意:在此示例中,我使用jQuery,因为它们的AJAX API非常棒\  n $ .ajax({
url:“http://example.com/page.php?params=1”
})
.done(function(data){
//数据是我们的有效载荷\ n doSomethingWithPayload(data);
});
</ code> </ pre>

这样 doSomethingWithPayload </ code>已在客户端定义,并且每当调用时都会被调用 收到有效载荷。</ p>
</ div>

展开原文

原文

No, you cannot invoke JavaScript from the server-side. You can, however, have JavaScript loaded that makes calls to the server and retrieves data.

With that in mind you can have a call to retrieve JSON or XML from the server in which a payload resides that can be extracted by a JavaScript function that is already defined on the client-side.

// note: in this example I use jQuery because their AJAX API is terrific
$.ajax({
    url: "http://example.com/page.php?params=1"
})
.done(function( data ) {
    // data is our payload
    doSomethingWithPayload(data);
});

That way doSomethingWithPayload already is defined on the client, and is called whenever the payload is received.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问