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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作