我想在JavaScript中设置一个提示框,并将输入的文本传递给我的细枝属性msg。
但是我不知道如何从脚本传递到树枝。
现在有我的代码。
extension Encodable {
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
public struct Customer: Codable {
public var companyName :String?
public var address :Address
public var contactName :String
public var email :String
public var mobile :String
public var website :String?
public var validTill :Date
public init?(dictionary: [String: Any]) {
guard let address = Address.init(dictionary:(dictionary["address"] as? [String:Any])!),
let contactName = dictionary["contactName"] as? String,
let email = dictionary["email"] as? String,
let mobile = dictionary["mobile"] as? String,
let validTill = dictionary["validTill"] as? Timestamp else {
return nil
}
self.address = address
self.contactName = contactName
self.email = email
self.mobile = mobile
self.companyName = dictionary["companyName"] as? String
self.website = dictionary["website"] as? String
self.validTill = validTill.dateValue()
}
public init?(companyName: String?, address: Address, contactName: String, email: String, mobile: String, website: String?, validTill: Date) {
self.companyName = companyName
self.address = address
self.contactName = contactName
self.email = email
self.mobile = mobile
self.website = website
self.validTill = validTill
}
}
答案 0 :(得分:0)
这里似乎存在一个基本的误解。在JS接近执行之前,Twig代码在服务器上运行。执行完Twig代码后,然后将生成的页面转到浏览器并执行JS。
实际上,这个问题是“我的代码如何及时返回”?
我建议使用Javascript路由系统(https://symfony.com/doc/current/routing/generate_url_javascript.html)直接在Javascript中生成所需的网址。看起来像
// JAVASCRIPT
var url = Routing.generate('email_index', {
'iduser': iduser,
'msg': saisie
});
好的,您已经问了一个后续问题,关于如何将它们放在一起。我建议不要使用button元素的onclick
属性:这可能是您在课堂上所做的,但被认为已过时。获取对您的按钮的引用:
var myButton = document.querySelector("button");
将iduser
值传递到Javascript(两个选项之一):
var iduser = {{ onlineorder.iduser.iduser }}; // if it's an int
var iduser = "{{ onlineorder.iduser.iduser | e('js') }}"; // if it's a string.
// the e('js') is a Twig function to safely generate Javascript strings, see
// https://twig.symfony.com/doc/2.x/filters/escape.html
然后使用上面的第一个代码块生成url
。
最后在按钮上设置事件处理程序:(docs)
button.addEventListener("click", function(event) {
window.location.href = url;
});
如果您还有其他问题,建议您咨询您的讲师/主管。