dousi2013 2015-01-16 11:56
浏览 31
已采纳

我可以通过链接回复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.

  • 写回答

1条回答 默认 最新

  • dpevsxjn809817 2015-01-16 12:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog