如何从自定义HTML/CSS页面调用生成二维码的Azure Function?
回答:在HTML页面中调用生成二维码的Azure Function
Great job getting your QR code-generating Azure Function up and running! Let's walk through how to call it from your custom HTML/CSS page step by step.
核心思路
Your Azure Function uses an HttpTrigger and returns a data URL (a base64-encoded string representing the QR code image). So we just need to:
- Create a simple UI with input for the text, a trigger button, and an area to display the QR code
- Use JavaScript to send a GET request to your Azure Function's endpoint with the text parameter
- Take the returned data URL and load it into an
<img>element to show the QR code
Step 1: Prepare your Azure Function for cross-origin requests (CORS)
First, if your HTML page is hosted on a different domain than your Azure Function (which it almost certainly is), you need to enable CORS in your Function App:
- Go to the Azure Portal and navigate to your Function App
- Under API in the left menu, select CORS
- Add the origin of your HTML page (e.g.,
http://localhost:5500for local testing, or your production domain). You can also use*for testing purposes (not recommended for production).
Step 2: Full HTML/CSS/JS Example
Here's a complete self-contained page that calls your Azure Function:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>QR Code Generator</title> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 2rem auto; padding: 0 1rem; } .qr-container { margin-top: 2rem; padding: 1rem; border: 1px solid #eee; border-radius: 8px; text-align: center; } input[type="text"] { width: 100%; padding: 0.8rem; margin-bottom: 1rem; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } button { padding: 0.8rem 1.5rem; background-color: #0078d4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; } button:hover { background-color: #005a9e; } #qrImage { max-width: 100%; margin-top: 1rem; display: none; /* Hide until we have a QR code */ } .error-message { color: #d93025; margin-top: 1rem; display: none; } </style> </head> <body> <h1>Generate QR Code</h1> <input type="text" id="textInput" placeholder="Enter text to encode in QR code"> <button id="generateBtn">Generate QR Code</button> <div class="qr-container"> <img id="qrImage" alt="Generated QR Code"> <div id="errorMsg" class="error-message"></div> </div> <script> // Replace this with your Azure Function's actual URL const AZURE_FUNCTION_URL = "https://your-function-app-name.azurewebsites.net/api/YourFunctionName?code=your-function-key"; const generateBtn = document.getElementById('generateBtn'); const textInput = document.getElementById('textInput'); const qrImage = document.getElementById('qrImage'); const errorMsg = document.getElementById('errorMsg'); generateBtn.addEventListener('click', async () => { const text = textInput.value.trim(); // Clear previous state qrImage.style.display = 'none'; errorMsg.style.display = 'none'; errorMsg.textContent = ''; if (!text) { errorMsg.textContent = 'Please enter some text to encode'; errorMsg.style.display = 'block'; return; } try { // Send GET request to Azure Function with the text parameter const response = await fetch(`${AZURE_FUNCTION_URL}&text=${encodeURIComponent(text)}`); if (!response.ok) { throw new Error(`Request failed: ${response.statusText}`); } const dataUrl = await response.text(); // Load the data URL into the image element qrImage.src = dataUrl; qrImage.style.display = 'block'; } catch (err) { errorMsg.textContent = `Failed to generate QR code: ${err.message}`; errorMsg.style.display = 'block'; console.error('Error:', err); } }); // Optional: Allow pressing Enter to generate textInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { generateBtn.click(); } }); </script> </body> </html>
Key Details to Note
- Replace the Azure Function URL: Make sure to swap
AZURE_FUNCTION_URLwith your actual Function's endpoint. You can find this in the Azure Portal by going to your Function > Get function URL. encodeURIComponent: We use this to safely encode the input text (in case it contains spaces, special characters, etc.) before sending it as a query parameter.- Error Handling: The code handles empty input, failed requests, and displays user-friendly error messages.
- UI Feedback: The QR code image is hidden until it's successfully loaded, and error messages are only shown when something goes wrong.
Testing the Page
- Save the code above as an HTML file (e.g.,
qr-generator.html) - Replace the
AZURE_FUNCTION_URLwith your actual Function URL - Open the HTML file in a web browser (for local testing, you can use a simple server like VS Code's Live Server extension to avoid CORS issues with local
file://URLs) - Enter text, click the button, and you should see your QR code!
内容的提问来源于stack exchange,提问作者Gb Gb Any
相关产品推荐
相关产品推荐

