You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获JavaScript表单POST请求的响应并复用为变量?

How to Capture POST Request Response for Tableau Embed

Hey Miguel, great question! The problem with your current approach is that form.submit() triggers a full page reload, which makes it impossible to capture the response data and reuse it in your Tableau embed configuration. Instead, we need to send the POST request asynchronously using modern JavaScript APIs like fetch() so we can handle the response without navigating away from the page.

Here's a revised version of your code that captures the POST response and injects it into your Tableau embed:

<!DOCTYPE html>
<html>
<head>
    <title>Basic Embed</title>
    <script type="text/javascript" src="http://myserver/javascripts/api/tableau-2.min.js"></script>
    <script type="text/javascript">
        async function fetchTrustedTicket() {
            // Create form data matching your original hidden inputs
            const formData = new FormData();
            formData.append('username', 'user');
            formData.append('server', 'myserver');
            formData.append('client_ip', '');
            formData.append('target_site', 'site');

            try {
                // Send asynchronous POST request
                const response = await fetch('http://myserver/trusted', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`Request failed: ${response.status}`);
                }

                // Get the response text (adjust to response.json() if server returns JSON)
                const trustedTicket = await response.text();

                // Update the Tableau embed path with the captured ticket
                initTableauEmbed(trustedTicket);
            } catch (error) {
                console.error('Error fetching trusted ticket:', error);
                // Handle error case (e.g., show user message)
            }
        }

        function initTableauEmbed(trustedTicket) {
            // Update the Tableau placeholder with the valid ticket
            const tableauPlaceholder = document.querySelector('.tableauPlaceholder');
            tableauPlaceholder.innerHTML = `
                <object class='tableauViz' width='1000' height='977' style='display:block;'>
                    <param name='host_url' value='http://myserver/' />
                    <param name='site_root' value='&#47;t&#47;site' />
                    <param name='path' value='trusted/${trustedTicket}/t/site'/>
                </object>
            `;

            // Re-initialize the Tableau visualization if needed
            // If using the viz_v1.js API, you might need to create a new Viz instance here
            // Example: new tableau.Viz(tableauPlaceholder.querySelector('.tableauViz'), ...);
        }

        // Run the fetch when the page loads
        window.onload = fetchTrustedTicket;
    </script>
</head>
<body>
    <script type='text/javascript' src='http://myserver/javascripts/api/viz_v1.js'></script>
    <div class='tableauPlaceholder' style='width: 1000px; height: 977px;'>
        <!-- Content will be populated dynamically after fetching the ticket -->
    </div>
</body>
</html>

Key Changes Explained:

  • Asynchronous Request: We use fetch() (with async/await for readability) instead of a traditional form submit. This lets us stay on the same page and capture the response.
  • FormData: We construct a FormData object to match the hidden inputs from your original form—this ensures the server receives the same parameters as before.
  • Response Handling: We capture the server's response (assuming it's a plain-text ticket; switch to response.json() if the server returns JSON data) and pass it to initTableauEmbed().
  • Dynamic Tableau Setup: The initTableauEmbed() function updates the Tableau placeholder HTML with the valid ticket, replacing your placeholder text. Depending on your Tableau API version, you might need to explicitly initialize the Viz instance (commented example included).
  • Error Handling: We added a try/catch block to handle network errors or unsuccessful responses, so you can debug issues gracefully.

Important Notes:

  • Make sure your server allows cross-origin requests (CORS) if your HTML page is hosted on a different domain than myserver. If not, you might need to adjust server settings or use a proxy.
  • Verify the response format from your http://myserver/trusted endpoint—if it returns JSON instead of plain text, replace response.text() with response.json() and adjust how you extract the ticket value.

内容的提问来源于stack exchange,提问作者Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:43:33