使用jQuery UI Signature重绘保存的SVG签名失败,报语法错误
Hey there, let's break down what's going wrong here and fix that signature redraw issue.
The Root Cause
The error you're seeing happens because the signature("draw") method tries to parse any string input as JSON-formatted signature data first. But your sig variable holds an HTML-escaped SVG string (with < instead of <, > instead of >) — this isn't valid JSON, so the parser chokes on the first escaped character and throws that syntax error.
The Fix
You need to first convert that escaped SVG string back into a raw, unescaped SVG, then pass that to the draw method. Here's how to adjust your code:
var sig='<svg xmlns="https://www.w3.org/2000/svg"><g fill="#ddd"><rect x="0" y="0" width="300" height="100"/><g fill="none" stroke="#000000" stroke-width="2"><polyline points="43.84,15.22 46.84,17.22 49.84,22.22 52.84,28.22 55.84,33.22 59.84,40.22 62.84,54.22 62.84,58.22 62.84,61.22 59.84,65.22 58.84,65.22 58.84,63.22 59.84,57.22 64.84,49.22 79.84,44.22 86.84,44.22 88.84,44.22 89.84,51.22 86.84,56.22 83.84,59.22 71.84,61.22 65.84,61.22 63.84,59.22 61.84,56.22 61.84,54.22 64.84,50.22 102.84,44.22 155.84,41.22 192.84,41.22 233.84,40.22 234.84,40.22"/></g></g></svg>'; $("#theSignature").signature(); // Decode the HTML-escaped SVG string to get raw SVG content var rawSvg = $("<div>").html(sig).text(); // Now pass the raw SVG to draw the signature $("#theSignature").signature("draw", rawSvg);
Bonus: Avoid This Issue in the Future
If you're saving the signature from the frontend yourself, skip the HTML escaping entirely. Use the plugin's built-in toSVG() method to get the raw SVG string directly, then store that:
// When saving the signature var savedSvg = $("#theSignature").signature("toSVG"); // Store savedSvg directly (no escaping needed)
This way, when you retrieve it later, you can pass it straight to signature("draw") without needing to decode anything.
内容的提问来源于stack exchange,提问作者Shawn

